简体   繁体   English

如何过滤只有数字的简单多维数组

[英]How filter simple multidimensional array with only numbers

I have a multidimensional array like this: let arr = [ [1,2,3], [3,4,6], [4,5,7], [8,9,3]];我有一个这样的多维数组: let arr = [ [1,2,3], [3,4,6], [4,5,7], [8,9,3]];

and I need to use only a filter function for filtering this array.我只需要使用一个过滤器 function 来过滤这个数组。 I must filter the array and create a new array from the current inner arrays which contain the number 3:我必须过滤数组并从当前包含数字 3 的内部 arrays 创建一个新数组:

let myArr = [ [1,2,3], [3,4,6], [4,5,7], [8,9,3]];
function getVal(value, arr){    
    for(let i in arr){
        for(let j in arr[i]){
            if(arr[i][j] == value){
                return true;
            }
        }
    }

}

let newArr = myArr.filter(getVal(3, myArr));

My code is not working.我的代码不起作用。 Actually, it's working, but I don`t see any result.实际上,它正在工作,但我没有看到任何结果。

The expected result is like this:预期的结果是这样的:

newArr = [[1,2,3], [3,4,6], [8,9,3]];

All I have found are filter methods with objects.我发现的只是带有对象的过滤方法。

You need a different style of the callback.您需要不同风格的回调。

 const contains = v => a => a.includes(v); var array = [[1, 2, 3], [3, 4, 6], [4, 5, 7], [8, 9, 3]], result = array.filter(contains(3)); console.log(result);

Assuming that it is 2 dimensional array.假设它是二维数组。 Use indexOf to check inside arrays:使用 indexOf 检查 arrays 内部:

myArr.filter((a)=> { return a.indexOf(3)>=0})
cont result = arr.filter(a => a.includes(3));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM