I have an array of JavaScript objects that contain an object which includes a price attribute. How to sort it by price?
Following is my input array.
const products = [
{
ratingReviews: '264 отзыва',
price: {
oldUan: '4 333 грн',
newUan: '3 799 грн',
},
name: 'Motorola MOTO G4 (XT1622) Black',
}, {
ratingReviews: '488 отзывов',
price: '6 199 грн',
name: 'Samsung Galaxy J7 (2016) J710F/DS Gold + защитное стекло + чехол!',
}, {
ratingReviews: '198 отзывов',
price: {
oldUan: '3 495 грн',
newUan: '2 995 грн',
},
name: 'Lenovo K5 (A6020a40) Silver',
}]
Below is my code and it is not working correctly.
function makeNumber(string) {
const reg = /\d+/g
if(reg.test(string)){
let numberStr = string.match(reg)
const number = [...numberStr]
return +number.join('')
}
return ''
}
function compare(a, b) {
if (b.price.hasOwnProperty('newUan')) {
b = makeNumber(b.price.newUan)
a = makeNumber(a.price.newUan)
} else {
b = makeNumber(b.price)
a = makeNumber(a.price)
}
return b - a
}
const sortedByPrice = () => {
return products.sort(compare)
}
Your compare method should need some modifications.
function compare(a, b) {
if (a.price.hasOwnProperty('newUan')) {
a = makeNumber(a.price.newUan)
}
if (b.price.hasOwnProperty('newUan')) {
b = makeNumber(b.price.newUan)
}
b = makeNumber(b.price)
a = makeNumber(a.price)
return b - a
}
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.