Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

127
Vistas
Sort 2D array by matching the last values with the first one in the next index

So basically, I have this array

array = [[1,0],[2,1],[0,3],[3,2]]

Is there any quick method to convert the array to look like this

array = [[0,3],[3,2],[2,1],[1,0]]

What I want is for the first element of the new array to be always contain 0 in the first spot of the nested array. That's easy enough, because the sort() function does exactly that; the hard part is ordering the new array like the one above.

In the most simplest terms, I'd like for nested arrays to be "connected": see how the 3 of the first nested array matches the other 3 to its right and so on.

Feel free to leave any comments so I can try to explain the problem a little bit better.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

For the example you gave the easiest solution would be to sort the 2d array by the second element of each inner array, as follow:

let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);

In that way you can sort the array with the sort method according to the elements in the inner arrays.

let array = [[1,0],[2,1],[0,3],[3,2]];
array.sort((a, b) => b[1] - a[1]);
console.log(array);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Look at this method:

const array =  [[1,0],[2,1],[0,3],[3,2]];
const result = [...array];

// Put the subarray with the zero element first
// You can use the sort() function but I guess this method
// performs better in terms of time

for (let i = 0; i < result.length; ++i) {
  if (result[i][0] === 0) {
    result.unshift(...result.splice(i, 1));
    break;
  }
}

// Now reorder the array so that the last index of a subarray 
// matches with the first index of the other subarray

for (let i = 0; i < result.length; ++i) {
  for (let j = i + 1; j < result.length; ++j) {
    if (result[i][1] === result[j][0]) {
      // recollocate the subarray so that it matches the way we want
      result.splice(i + 1, 0, ...result.splice(j, 1));
      break;
    }
  }
}

console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could take an object as reference and rebuild the array by taking the chained items.

const
    getItems = (reference, value) => {
        const a = reference[value];
        return a ? [a, ...(a[1] === 0 ? [] : getItems(reference, a[1]))] : [];
    },
    array = [[1, 0], [2, 1], [0, 3], [3, 2]],
    reference = array.reduce((r, a) => (r[a[0]] = a, r), {}),
    result = getItems(reference, 0);

console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda