Looking to search a value in an array of array and returning index. Most of the answers are array of objects. So I am looking to search for eg 22 and get 2 as the index where the value was found
Here is the code pen https://codesandbox.io/s/lodash-playground-array-pzzhe
const arr = [["a","b"],["f","r"],["r",22,"t"]]; console.log("arr", arr);
You could take plain Javascript with Array#findIndex
with Array#includes
.
var array = [["a", "b"], ["f", "r"], ["r", 22, "t"]], value = 22, index = array.findIndex(a => a.includes(value)); console.log(index);
Option 1 Use findIndex
const arr = [["a","b"],["f","r"],["r",22,"t"]]; console.log(arr.findIndex(a => a.includes(22)));
Option 2 : Use functions indexOf and includes :
const arr = [["a","b"],["f","r"],["r",22,"t"]]; // find element const element = arr.find(a => a.includes(22)); // find element index const currentIndex = arr.indexOf(element) console.log(currentIndex);
indexOfFlat = (val, array) => array.findIndex(_arr => _arr.includes(val)); const arr = [["a","b"],["f","r"],["r",22,"t"]]; console.log("arr", arr); console.log("index", indexOfFlat(22, arr))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>
In case you would actually need the sub-array in which the value was found, you could also use Array.find
and its index
and get both:
const arr = [["a","b"],["f","r"],["r",22,"t"]]; let index, subArr = arr.find((x,i) => x.includes(22) && ~(index=i)) console.log('sub-array: ', subArr) console.log('index: ', index)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.