简体   繁体   English

按值查找嵌套数组

[英]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,如果item是一个数组,
  • if item has the same length as the wanted value array and如果 item 的长度与所需的值数组相同,并且
  • 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() ?您是否正在寻找类似find()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.但是,您可以将该值转换为 json 字符串并进行比较,但是,这需要两个数组中的确切顺序。

 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()您可以将过滤器与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 :您可以使用.findJSON.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:检查两个数组是否相等的更好方法是使用.every.includes ,如下所示:

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

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

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