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

112
Vistas
Sort array of objects based on best matching another array

I have an array of strings which can be seen as a template / reference:

// Template
let template = ['A', 'B', 'C'];

I also have an array of objects containing some of the array's strings:

// Source (to be sorted)
let source = [
   { items: ['B', 'D', 'E'] },
   { items: ['E', 'L', 'Y'] },
   { items: ['G', 'B', 'A'] },
   { items: ['C', 'B', 'A'] }
];

I now need to find a way to sort the items in the source array by matching to the template array (from best to worst). The order of the strings in the items is irrelevant.

Based on my example above, the result after sorting would look like this:

// Result after sorting
let sorted = [
   { items: ['C', 'B', 'A'] }, // 3 matches (A, B, C)
   { items: ['G', 'B', 'A'] }, // 2 matches (A, B)
   { items: ['B', 'D', 'E'] }, // 1 match (B)
   { items: ['E', 'L', 'Y'] } // no match
];

With the JavaScript method .sort() and .localCompare() I can sort an array based on strings but I couldn't find a way to sort by a given array 'template'.

I would be more than happy if somebody knows a way how to do that? Thank you in advance!

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

0

You can base your logic on the size of the Set that contains distinct elements from both template and items. The smaller the Set, the more common items:

const template = ['A', 'B', 'C'];

const source = [
   { items: ['B', 'D', 'E'] },
   { items: ['E', 'L', 'Y'] },
   { items: ['G', 'B', 'A'] },
   { items: ['C', 'B', 'A'] }
];

const target = source
  .map(({items}) => ({items, size: new Set([...items, ...template]).size}))
  .sort((a, b) => a.size - b.size);

console.log(target);

In case you're not dealing with distinct values in your arrays, this might be more appropriate:

const template = ['A', 'B', 'C'];

const source = [
   { items: ['B', 'D', 'E'] },
   { items: ['E', 'L', 'Y'] },
   { items: ['G', 'B', 'A'] },
   { items: ['C', 'B', 'A'] }
];

const target = source
  .map(({items}) => ({
    items,
    size: items.reduce((a, v) => a + template.includes(v), 0)
  }))
  .sort((a, b) => b.size - a.size);

console.log(target);

This can again be further optimized by converting the template to a Set.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You simply need to build a proper sorting function that compares 2 array elements. For example you can count items matching your template.

function sortByMatch(template) {
  const items = new Set(template)
  
  const rank = arr => arr.filter(item => items.has(item)).length
  
  return (a, b) => rank(b.items) - rank(a.items)
}

let template = ['A', 'B', 'C'];

let source = [
   { items: ['B', 'D', 'E'] },
   { items: ['E', 'L', 'Y'] },
   { items: ['G', 'B', 'A'] },
   { items: ['C', 'B', 'A'] }
];

const sorted = source.slice().sort(sortByMatch(template))

console.log(sorted.map(item => item.items.join(', ')))

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