Skip to content Skip to sidebar Skip to footer

Javascript Sort Items Excluding Some Specific Items

I am trying to sort some items (sort a map) , I can sort it successfully, but I want to exclude some items based on it's attribute Right now I am sorting like this based on attrib

Solution 1:

You can sort the wanted item to front by using a check and return the delta of the check.

var array = [{ product_id: 1, price: 1 }, { product_id: 2, price: 3 }, { product_id: 3, price: 4 }, { product_id: 4, price: 1 }, { product_id: 5, price: 8 }, { product_id: 5677, price: 1 }];

array.sort(function (a, b) {
    return (b.product_id === 5677) - (a.product_id === 5677) || b.price - a.price;
});

console.log(array);
.as-console-wrapper { max-height: 100%!important; top: 0; }

With more than just one id for sorting to top

var array = [{ product_id: 1, price: 1 }, { product_id: 2, price: 3 }, { product_id: 3, price: 4 }, { product_id: 4, price: 1 }, { product_id: 5, price: 8 }, { product_id: 5677, price: 1 }];
    topIds = [5677, 2]

array.sort(function (a, b) {
    return topIds.includes(b.product_id) - topIds.includes(a.product_id) || b.price - a.price;
});

console.log(array);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Post a Comment for "Javascript Sort Items Excluding Some Specific Items"