简体   繁体   中英

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]];

and I need to use only a filter function for filtering this array. I must filter the array and create a new array from the current inner arrays which contain the number 3:

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:

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

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.

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