How to sort in a specific order - Array prototype (not by value or by name)
I want to sort an array of three lines in a specific order.
book, car and wheel.
I can get these lines in any order. There can be one or more lines - maximum three
I would like to sort the rows in the following exact order if one or more rows are received.
wheel, book, car
Suppose property name is name ...
I've tried something like this:
myitem.sort((a, b) => {
if(a.name === 'wheel')
return 1;
if(a.name === 'book' && b.name === 'car')
return 1;
return -1;
source to share
You can use an object with an order of values ββand their order. With the default, you can move unspecified values ββto the beginning or end of the array.
var order = { wheel: 1, book: 2, car: 3, default: 1000 },
array = ['foo', 'car', 'book', 'wheel'];
array.sort(function (a, b) {
return (order[a] || order.default) - (order[b] || order.default);
});
console.log(array);
source to share
Since you are expecting instances (only in myitem
) of these three lines, you can use filter
in an ordered array and check for the presence of those input lines with Set#has
:
var result = ['wheel', 'book', 'car'].filter(function (s) {
return this.has(s)
}, new Set(myitem));
// Sample data being received
var myitem = ['car', 'wheel'];
var result = ['wheel', 'book', 'car'].filter(function (s) {
return this.has(s)
}, new Set(myitem));
// ordered result
console.log(result);
source to share
Your code looks mostly correct. I fixed the formatting etc. And changed the signs in the sort function.
Of course, this only handles sorting items with these three exact names. If you need to handle other inputs, you have to decide what happens to them.
var myitems = [
{
name: "book",
},
{
name: "wheel",
},
{
name: "car",
},
];
console.log(
myitems.sort((a, b) => {
if (a.name === "wheel") {
return -1;
}
if (a.name === "book" && b.name === "car") {
return -1;
}
return 1;
})
);
source to share