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

164
Visualizações
How to sort an array of objects based on the substring of property values

How can I sort the following array, in a custom order, based on the prop2's last 3 letters that have to be in this order 'ABR', 'FDE', 'ZFR' and also in descending order 'ZFR', 'FDE', 'ARB' for another array.

Sample input:

const arr = [
  { prop1: 3, prop2: '3FDE' },
  { prop1: 4, prop2: '5ZFR' },
  { prop1: 5, prop2: '7ABR' }
]

Expected output:

const arr1 = [
  { prop1: 5, prop2: '7ABR' },
  { prop1: 3, prop2: '3FDE' },
  { prop1: 4, prop2: '5ZFR' }
]

and

const arr2 = [
  { prop1: 4, prop2: '5ZFR' },
  { prop1: 3, prop2: '3FDE' },
  { prop1: 5, prop2: '7ABR' }
]
about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

You can use the Array#sort, String#substring or String#slice or String#substr and the String#localCompare methods as follows:

  • substring

const arr = [ {prop1:4, prop2:'5ZFR'}, {prop1:5, prop2:'7ABR'}, {prop1:3, prop2:'3FDE'} ];

const output = arr.sort(
   (a,b) => 
   a.prop2.substring(1).localeCompare( b.prop2.substring(1) )
);

console.log( output );

With slice or substr you can use a negative n to indicate the last n characters:

const arr = [ {prop1:4, prop2:'5ZFR'}, {prop1:5, prop2:'7ABR'}, {prop1:3, prop2:'3FDE'} ];

const output = arr.sort(
   (a,b) => 
   a.prop2.slice(-3).localeCompare( b.prop2.slice(-3) )
);

console.log( output );

about 4 years ago · Santiago Gelvez Relatório

0

  • Using Array#sort, iterate over the array to sort it
  • In every iteration, use String#substr to get the last 3 characters and String#localeCompare to compare the two strings

const arr = [ { prop1: 3, prop2: '3FDE' }, { prop1: 4, prop2: '5ZFR' }, { 
prop1: 5, prop2: '7ABR' } ];

const _getLastThree = (str = '') => str.substr(str.length - 3);
const res = arr.sort(({ prop2: a }, { prop2: b }) => 
  _getLastThree(a).localeCompare(_getLastThree(b))
);

console.log(res);

about 4 years ago · Santiago Gelvez Relatório

0

Just use .localeCompare() in combination with .slice():

const arr=[
{prop1:5, prop2:'7ABR'},
{prop1:3, prop2:'3FDE'},
{prop1:4, prop2:'5ZFR'},
]


var ascArr,dscArr;
console.log(ascArr=arr.slice(0).sort((a,b)=>a.prop2.slice(-3).localeCompare(b.prop2.slice(-3))));

// for descending order just do 
console.log(dscArr=arr.slice(0).sort((a,b)=>-a.prop2.slice(-3).localeCompare(b.prop2.slice(-3))));

// or reverse the resulting array with 
console.log(dscArr=ascArr.reverse());

Please note that the two slice() methods belong to different prototypes: .slice(0) is an Array method that essentially creates a flat copy of the original array while .slice(-3) is a String method that "shaves off" the last three characters of the string.

about 4 years ago · Santiago Gelvez 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