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?
4 Answers 4
You need to check
- if
itemis 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);
}
}
Comments
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")
}
Comments
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");
}
}
1 Comment
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);
JSON.stringifyfor this as too many answers show. That's not a sensible means of simple value comparison.