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

340
Views
Re-order an array of objects when an object contains a value

I want to move items to the top of my array when the values are found within another array.

const data = [
   { value: 'BMW', count: 1 },
   { value: 'AUDI', count: 1 },
   { value: 'VAUXHALL', count: 1 },
   { value: 'FIAT', count: 1 },
   { value: 'HONDA', count: 1 },
   { value: 'LANDROVER', count: 1 },
];

const selected = [ 'AUDI', 'HONDA' ];

So basically the above will turn into:

const data = [
   { value: 'AUDI', count: 1 },
   { value: 'HONDA', count: 1 },
   { value: 'BMW', count: 1 },
   { value: 'VAUXHALL', count: 1 },
   { value: 'FIAT', count: 1 },
   { value: 'LANDROVER', count: 1 },
];

This is what I have at the moment, however it doesn't work as expected and it's not nice at all:

let prepend = [];
selected.forEach(selected => {
    for (let i = 0; i < data.length; i++) {
        if (data[i] && data[i].value === selected) {
            prepend.push(data[i]);
            delete data[i];
            break;
        }
    }
})
data.unshift(...prepend);
data = data.filter(Boolean);

I want to do something cleaner like this:

return [...data].sort((a, b) => {

});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can take advantage of boolean arithmetic operations with Array#includes and Array#sort.

const data = [
   { value: 'BMW', count: 1 },
   { value: 'AUDI', count: 1 },
   { value: 'VAUXHALL', count: 1 },
   { value: 'FIAT', count: 1 },
   { value: 'HONDA', count: 1 },
   { value: 'LANDROVER', count: 1 },
];

const selected = [ 'AUDI', 'HONDA' ];

data.sort((a, b) => selected.includes(b.value)  - selected.includes(a.value))
console.log(data);

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!