gpt4 book ai didi

javascript - 通过方法对数组中的对象进行排序

转载 作者:行者123 更新时间:2023-11-30 11:05:41 24 4
gpt4 key购买 nike

此函数对数组进行排序。首先,应显示国家/地区等于第二个参数中指定的国家/地区的对象。然后剩下的。但是我不明白哪里出了问题?

 
const arr = [
{
"name":"BMW",
"price":"55 000",
"country":"Germany",
"certificate":"yes"
},
{
"name":"Mitsubishi",
"price":"93 000",
"constructor":"Bar John",
"door":"3",
"country":"Japan",
},
{
"name":"Mercedes-benz",
"price":"63 000",
"country":"Germany",
"certificate":"yes"
},
{
"name":"TOYOTA",
"price":"48 000",
"max_people":"7",
"country":"Japan",
"certificate":"yes"
},
{
"name":"Volkswagen",
"price":"36 000",
"constructor":"Pier Sun",
"country":"Germany",
"certificate":"no"
},
];

function countries(arr,country){
let one = arr.sort(function(item){
return country > item.country;
});
return one;
}

console.log(countries(arr,"Japan"));

最佳答案

您需要将这两个对象与想要的国家进行比较并将此项目移至顶部。

Array#sort改变数组的顺序。

function countries(array, country) {
return array.sort(({ country: a }, { country: b }) => (b === country) - (a === country));
}

const array = [{ name: "BMW", price: "55 000", country: "Germany", certificate: "yes" }, { name: "Mitsubishi", price: "93 000", constructor: "Bar John", door: "3", country: "Japan" }, { name: "Mercedes-benz", price: "63 000", country: "Germany", certificate: "yes" }, { name: "TOYOTA", price: "48 000", max_people: "7", country: "Japan", certificate: "yes" }, { name: "Volkswagen", price: "36 000", constructor: "Pier Sun", country: "Germany", certificate: "no" }];

console.log(countries(array, "Japan"));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 通过方法对数组中的对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55724182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com