话不多说直接上代码注解
const removeResorting = () => {
let list = [
{ name: "66", value: 1 },
{ name: "88", value: 2 },
{ name: "99", value: 1 },
{ name: "66", value: 3 },
{ name: "99", value: 2 },
];
list = list
.filter((item, index, self) => {
return (
self.findIndex(
(item2) => JSON.stringify(item2) === JSON.stringify(item)
) === index
);
})
.sort((a, b) => {
return a.name.localeCompare(b.name);
});
console.log(list);
};
removeResorting
使用Array.prototype.filter()
来去除数组中的重复项,遍历数组的每一个元素,然后使用Array.prototype.findIndex()
来找到与当前元素相同的元素的索引。如果这个索引与当前元素的索引相同,那么就保留这个元素,否则就过滤掉。
之后,这个方法使用Array.prototype.sort()
方法来对数组进行排序。这里使用了localeCompare
方法,它根据本地语言环境的字符串排序规则来对字符串进行排序