0

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.

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming that it is 2 dimensional array. Use indexOf to check inside arrays:

myArr.filter((a)=> { return a.indexOf(3)>=0})

Comments

0
cont result = arr.filter(a => a.includes(3));

1 Comment

Please don't post only code as an answer, but include an explanation what your code does and how it solves the problem of the question. Answers with an explanation are generally of higher quality, and are more likely to attract upvotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.