0

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?

I tried

arr.filter(id => id === specificValue);

Thanks for the help

4
  • 1
    Try combining includes with the filter you're currently using. Commented Feb 15, 2022 at 16:45
  • 1
    Using Lodash's flattenDeep: _.flattenDeep(arr).find(specificValue). Commented Feb 15, 2022 at 16:46
  • 1
    Try flat array arr.flat().filter(id => id === specificValue); Commented Feb 15, 2022 at 16:46
  • 2
    arr is an array. The elements in arr are arrays. Have a look at the other methods of Array (but it would also already work with just .filter()) Commented Feb 15, 2022 at 16:47

3 Answers 3

2

Let's keep going with your attempt.

The problem is your array is nested so array.filter will not work

Use array.flat with array.filter:

let arr = [['123456','234567'], ['345678']];
let specificValue = '123456';
console.log(arr.flat().filter(i=>i==specificValue))

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

Comments

2

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

Comments

1

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:

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.