Home > Mobile >  Sorting object array by a property value
Sorting object array by a property value

Time:03-11

I have this array ob objects that I need to sort by their number

var products = [
{
 name: 'Gift Box',
 productNumber: '44',
 SKU: 'ABCD'
},
{
 name: 'Tabletop Game',
 productNumber: '63',
 SKU: 'DEFG'
},
{
 name: 'Poker Deck',
 productNumber: '25s',
 SKU: 'HIJK'
},
{
 name: 'Box of chocolates',
 productNumber: '96p',
 SKU: 'LMNO'
},
{
 name: 'Box of Swiss chocolates',
 productNumber: '96s',
 SKU: 'PQRS'
},
{
 name: 'Gift card',
 productNumber: '81',
 SKU: 'TUVW'
}];

As you can see, some of the productNumber properties have a letter in them, and as such, I think is not going to be as easy as just doing a products.sort((a, b) => parseInt(b.productNumber) - parseInt(a.productNumber));, so, how can I solve this?

CodePudding user response:

For completeness only:

console.log(parseInt('44a')); // 44

Your approach with parseInt

products.sort((a, b) => parseInt(b.productNumber) - parseInt(a.productNumber));

works.

CodePudding user response:

Just match the numeric part first?

const products=[{name:"Gift Box",productNumber:"44",SKU:"ABCD"},{name:"Tabletop Game",productNumber:"63",SKU:"DEFG"},{name:"Poker Deck",productNumber:"25s",SKU:"HIJK"},{name:"Box of chocolates",productNumber:"96p",SKU:"LMNO"},{name:"Box of Swiss chocolates",productNumber:"96s",SKU:"PQRS"},{name:"Gift card",productNumber:"81",SKU:"TUVW"}];

const toNum = obj => obj.productNumber.match(/\d /)[0];
products.sort((a, b) => toNum(b) - toNum(a));
console.log(products);

  • Related