简体   繁体   中英

Find nested array by value

I've searched high and low for an answer to this, but nothing.

I have a nested array and want to find it by exact value but can't seem to get it to work:

let rowLetters = ["A","B","C",["D","E"],"F"];

for(n=0;n<rowLetters.length;n++){
    if(rowLetters[n] === ["D","E"]){
        console.log("Found");
    }
    console.log(rowLetters[n]);
}

Console Output:

"A"
"B"
"C"
["D","E"] // <-- There it is..
"F"

What am I doing wrong?

You need to check

  • if item is an array,
  • if item has the same length as the wanted value array and
  • if the values of the arrays are equal.

 let rowLetters = ["A", "B", "C", ["D", "E"], "F"], search = ["D", "E"]; for (const item of rowLetters) { if (Array.isArray(item) && item.length === search.length && search.every((v, i) => item[i] === v)) { console.log(item); } }

Are you looking for something like find() mixed with Array.isArray() ?

 let rowLetters = ["A","B","C",["D","E"],"F"]; console.log(rowLetters.find(i => Array.isArray(i)))

You cannot compare an array to an array because you are comparing by a reference and not a value. You can however cast the value to a json string and compare, however, this requires exact order in both arrays.

 let rowLetters = ["A","B","C",["D","E"],"F"]; for(let i of rowLetters){ if(JSON.stringify(i) === JSON.stringify(["D","E"])) { console.log("Found"); } }

You can use filter with JSON.stringify()

 let data = ["A", "B", "C", ["D", "E"], "F"]; let search = data.filter(ele => JSON.stringify(ele) == JSON.stringify(["D", "E"])); if (search.length > 0) { console.log("found") }

You can use .find and JSON.stringify :

 let rowLetters = ["A","B","C",["D","E"],"F"]; let arrayToFind = JSON.stringify(["D","E"]) let nestedArray = rowLetters.find( arr => JSON.stringify(arr) === arrayToFind ); console.log(nestedArray);

A better way to check if two arrays are equal would be using .every and .includes as follows:

 let rowLetters = ["A","B","C",["D","E"],"F"]; const arraysAreEqual = (arr1, arr2) => { if(arr1.length != arr2.length) return false; return arr1.every( e => arr2.includes(e) ); } const arrayToFind = ["D","E"]; let nestedArray = rowLetters.find( arr => arraysAreEqual(arr, arrayToFind) ); console.log(nestedArray);

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