4 回答
TA贡献1856条经验 获得超11个赞
您可以给每个name案例打分,然后在Array.sort函数中使用该分数。
const data = [
{ name: 'John', gender: 'Male', id: '1' },
{ name: 'Max', gender: 'Male', id: '2' },
{ name: 'John', gender: 'Male', id: '3' },
{ name: 'Sam', gender: 'Male', id: '4' },
{ name: 'Max', gender: 'Male', id: '5' },
{ name: 'Sam', gender: 'Male', id: '6' },
{ name: 'Sam', gender: 'Male', id: '7' },
{ name: ' ', gender: 'Male', id: '8' },
{ name: 'John', gender: 'Male', id: '9' },
{ name: ' ', gender: 'Male', id: '10' }
];
const getScore = name => {
if (name === 'Max') return 3;
else if (name === 'Sam') return 2;
else if (name === 'John') return 1;
else return 0;
};
data.sort((a, b) => getScore(b.name) - getScore(a.name));
console.log(data);
TA贡献1830条经验 获得超3个赞
您可以执行以下操作,
data = [
{"name": "John", "gender": "Male", "id": "1"},
{"name": "Max", "gender": "Male", "id": "2"},
{"name": "John", "gender": "Male", "id": "3"},
{"name": "Sam", "gender": "Male", "id": "4"},
{"name": "Max", "gender": "Male", "id": "5"},
{"name": "Sam", "gender": "Male", "id": "6"},
{"name": "Sam", "gender": "Male", "id": "7"},
{"name": " ", "gender": "Male", "id": "8"},
{"name": "John", "gender": "Male", "id": "9"},
{"name": " ", "gender": "Male", "id": "10"},
]
data.sort((a, b) => {
if(a.name < b.name) {
return 1;
} else if(a.name > b.name) {
return -1;
}
return 0;
})
console.log(data);
TA贡献1818条经验 获得超3个赞
如果您的数据包含区分大小写的名称怎么办?
const getScore = name => {
if (name.toLowerCase() === 'max') return 3;
else if (name.toLowerCase() === 'sam') return 2;
else if (name.toLowerCase() === 'john') return 1;
else return 0;
};
data.sort((a, b) => getScore(b.name) - getScore(a.name));
console.log(data);
TA贡献1772条经验 获得超8个赞
您好,您可以使用此代码
var arr = [
{"name": "John", "gender": "Male", "id": "1"},
{"name": "Max", "gender": "Male", "id": "2"},
{"name": "John", "gender": "Male", "id": "3"},
{"name": "Sam", "gender": "Male", "id": "4"},
{"name": "Max", "gender": "Male", "id": "5"},
{"name": "Sam", "gender": "Male", "id": "6"},
{"name": "Sam", "gender": "Male", "id": "7"},
{"name": " ", "gender": "Male", "id": "8"},
{"name": "John", "gender": "Male", "id": "9"},
{"name": " ", "gender": "Male", "id": "10"},
];
var arr1 = arr.filter((value, index) => {
if(value.name == 'Max'){
return value
}
});
var arr2 = arr.filter((value, index) => {
if(value.name != 'Max'){
return value
}
});
arr2 = arr2.sort((a, b) => (a.name < b.name) ? 1 : -1);
var output = arr1.concat(arr2);
console.log(output);
添加回答
举报