На данный вопрос уже ответили:
Допустим, есть многомерный json-массив, состоящий из подобных элементов:
{
"manufacturer": "Apple",
"name": "iPhone",
"model": "7 Plus",
"memory": [
"32GB",
"128GB",
"256GB"
],
"colours": [
"Gold",
"Silver",
"Pink",
"Black"
],
"terms": [
{
"instalment_full_price": "49$/month",
"instalment_price": 49,
"price": 799
}
]
}
Как можно отсортировать между собой эти элементы по возрастанию цены по значению ключа terms[0].price?
Функция sort принимает в качестве аргумента функцию, которая в свою очередь получает 2 элемента. Их нужно сравнить и вернуть -1, 0 или 1. Подробнее на MDN.
const arr = [
{
"manufacturer": "Apple",
"name": "iPhone",
"model": "7 Plus",
"memory": [
"32GB",
"128GB",
"256GB"
],
"colours": [
"Gold",
"Silver",
"Pink",
"Black"
],
"terms": [
{
"instalment_full_price": "49$/month",
"instalment_price": 49,
"price": 7992
}
]
},
{
"manufacturer": "Apple",
"name": "iPhone",
"model": "7 Plus",
"memory": [
"32GB",
"128GB",
"256GB"
],
"colours": [
"Gold",
"Silver",
"Pink",
"Black"
],
"terms": [
{
"instalment_full_price": "49$/month",
"instalment_price": 49,
"price": 7991
}
]
},
{
"manufacturer": "Apple",
"name": "iPhone",
"model": "7 Plus",
"memory": [
"32GB",
"128GB",
"256GB"
],
"colours": [
"Gold",
"Silver",
"Pink",
"Black"
],
"terms": [
{
"instalment_full_price": "49$/month",
"instalment_price": 49,
"price": 79956
}
]
},
{
"manufacturer": "Apple",
"name": "iPhone",
"model": "7 Plus",
"memory": [
"32GB",
"128GB",
"256GB"
],
"colours": [
"Gold",
"Silver",
"Pink",
"Black"
],
"terms": [
{
"instalment_full_price": "49$/month",
"instalment_price": 49,
"price": 7995
}
]
}
]
const newArr = arr.sort((a,b) => a.terms[0].price > b.terms[0].price)
console.log(newArr)
Продвижение своими сайтами как стратегия роста и независимости