简体   繁体   中英

Sorting object array by a property value

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?

For completeness only:

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

Your approach with parseInt

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

works.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM