The code below should work but it doesn't. Does anyone know why?
const items = [
["bob", 5],
["jeff", 2],
["wal-E", 2],
["bob", 1],
["bob", 10]
];
items.indexOf(["bob", 5]);
//=> -1
CodePudding user response:
It does not because indexOf
uses simple comparison when looking for a match and [] !== []
because arrays are compared by reference, not by their contents. Try typing [5]===[5]
it will give you false.
So you will need to manually write comparison logic using findIndex
.
let items = [
["bob", 5],
["jeff", 2],
["wal-E", 2],
["bob", 1],
["bob", 10]
];
console.log(items.findIndex(x => x[0] === "bob" && x[1] === 5))
CodePudding user response:
Array#indexOf
uses strict equality ===
for comparison. What you're wanting to do can only work if you hold a reference to the same array:
const x = [1, 2];
[[0, 1], [1, 2], [2, 3]].indexOf(x);
//=> -1
[[0, 1], x, [2, 3]].indexOf(x);
//=> 1
What you can do is use Array#findIndex
and compare each element of each nested array with each element of x
at the same index:
const indexOf = (xs, ys) => ys.findIndex(yy => {
if (xs.length != yy.length) return false;
return yy.reduce((b, y, i) => b && Object.is(y, xs[i]), true);
});
indexOf([], [[1],[],[2, 3]]);
//=> 1
indexOf([1, 2], [[1, 2, 3, 4], [1, 2, 3], [1, 2]]);
//=> 2
indexOf([1, 2], [[2, 3], [3, 4]]);
//=> -1
indexOf([9, 9, 9], [[9], [9, 9], [9, 9, 9]]);
//=> 2
indexOf([9, NaN, 9], [[9], [9, NaN, 9], [9, 9]]);
//=> 1