• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

197
Views
Find index of nested array

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
almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

almost 3 years ago · Juan Pablo Isaza Report

0

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
almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error