0

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?

2 Answers 2

1

For completeness only:

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

Your approach with parseInt

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

works.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.