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

0

202
Views
Buscar índice de matriz anidada

El siguiente código debería funcionar, pero no lo hace. ¿Alguien sabe por qué?

 const items = [ ["bob", 5], ["jeff", 2], ["wal-E", 2], ["bob", 1], ["bob", 10] ]; items.indexOf(["bob", 5]); //=> -1
over 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

No lo hace porque indexOf usa una comparación simple cuando busca una coincidencia y [] !== [] porque las matrices se comparan por referencia, no por su contenido. Intente escribir [5]===[5] y obtendrá falso.

Por lo tanto, deberá escribir manualmente la lógica de comparación utilizando 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))

over 3 years ago · Juan Pablo Isaza Report

0

Array#indexOf usa igualdad estricta === para la comparación. Lo que desea hacer solo puede funcionar si tiene una referencia a la misma matriz:

 const x = [1, 2]; [[0, 1], [1, 2], [2, 3]].indexOf(x); //=> -1 [[0, 1], x, [2, 3]].indexOf(x); //=> 1

Lo que puede hacer es usar Array#findIndex y comparar cada elemento de cada matriz anidada con cada elemento de x en el mismo índice:

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