Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Tengo una lista en la matriz. ¿Cómo muestro que uno de sus elementos debe aparecer primero según la condición en el mapeo?

Aquí está el objeto.

 var arr = { firstValue:"xyz", content:[ { "value": "abc", "checked": true }, { "value": "xyz", "checked": false }, { "value": "lmn", "checked": true } ] }

En este firstValue es xyz, por lo que al mapear xyz debería aparecer primero de esta manera:

 var arr = { firstValue:"xyz", content:[ { "value": "xyz", "checked": true }, { "value": "abc", "checked": false }, { "value": "lmn", "checked": true } ] }

Cómo lograr esto usando javascript,

Gracias.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

const arr = { firstValue: "xyz", content: [ { value: "abc", checked: true, }, { value: "xyz", checked: false, }, { value: "lmn", checked: true, }, ], }; const index = arr.content.findIndex((item) => item.value === arr.firstValue); if (index !== -1 && index !== 0) { arr.content.unshift(...arr.content.splice(index, 1)); }
about 4 years ago · Juan Pablo Isaza Report

0

Parece que solo desea ordenar el objeto coincidente en la parte superior.

Puede usar Array#sort() , aunque esto mutará el objeto original, por lo que si está en estado, querrá clonarlo antes de ordenarlo.

 var arr = { firstValue: 'xyz', content: [ { value: 'abc', checked: true, }, { value: 'xyz', checked: false, }, { value: 'lmn', checked: true, }, ], }; const sorted = [...arr.content].sort((a, b) => (b.value === arr.firstValue) - (a.value === arr.firstValue)); console.log(sorted);

De lo contrario, puede encontrar el índice del objeto usando Array#findIndex() y luego usar Array#splice() y Array#unshift() para moverlo al principio de la matriz. Aquí declarando una función de utilidad y devolviendo una copia de la matriz pasada para evitar la mutación.

 var arr = { firstValue: 'xyz', content: [ { value: 'abc', checked: true, }, { value: 'xyz', checked: false, }, { value: 'lmn', checked: true, }, ], }; const orderFirst = (a) => { const res = [...a]; const i = a.findIndex((o) => o.value === arr.firstValue); if (i && i !== -1) { res.unshift(res.splice(i, 1)); } return res; }; const sorted = orderFirst(arr.content); console.log(sorted);

about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!