I wish to sort an array of three strings in a specific order.
book, car and wheel.
I can receive these strings in any order. There may be one or more string
Your code looks mostly right. I fixed the formatting, etc. and reversed the signs in the sort function.
Of course, this only handles sorting items with those three exact names. If you need to handle other inputs, you'll have to decide what should happen to those.
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;
})
);
Since you expect instances (in myitem
) of these three strings only, you can use filter
on the ordered array, and test the presence of these input strings 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);
You could use an object with the order of the values and their order. With a default value, you could move not specified values to start 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);