[英]How can I find a specific value inside a nested array?
Question: I have this array that have a nested array that I want to loop to find a specific value.问题:我有一个包含嵌套数组的数组,我想循环查找特定值。
arr = [['123456','234567'], ['345678']];
specificValue = '123456';
The output that I want is to find out if there's a value same with specificvalue and return this value?我想要的output是找出是否有一个与specificvalue相同的值并返回这个值?
I tried我试过了
arr.filter(id => id === specificValue);
Thanks for the help谢谢您的帮助
Try this code试试这个代码
const arr = [['123456','234567'], ['345678']]; const result = arr.flat(Infinity).find(val => val === "123456"); console.log(result);
You can learn more about array.flat() method here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat您可以在此处了解有关array.flat()方法的更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Let's keep going with your attempt.让我们继续你的尝试。
The problem is your array is nested so array.filter
will not work问题是你的数组是嵌套的,所以array.filter
不起作用
Use array.flat
with array.filter
:将array.flat
与array.filter
一起使用:
let arr = [['123456','234567'], ['345678']]; let specificValue = '123456'; console.log(arr.flat().filter(i=>i==specificValue))
Since flat() takes a depth as an argument, to be able to search in an indefinite number of nested arrays you could try good old recursion:由于 flat() 将深度作为参数,因此为了能够在无限数量的嵌套 arrays 中进行搜索,您可以尝试良好的旧递归:
const findRecursive = (array, target) => {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) {
return array[i];
} else if (Array.isArray(array[i])) {
return findRecursive(array[i], target);
}
}
}
console.log(findRecursive(arr, specificValue));
EDIT: Abdelrhman Mohamed has corrected me, you can specify an indefinite amount of nested arrays using array.flat(Infinity)
编辑:Abdelrhman Mohamed 纠正了我,您可以使用array.flat(Infinity)
指定无限数量的嵌套 arrays
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.