Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda