3

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 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.