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

Viewed 58

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) => {

});
1 Answers

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);

Related