分组
const map = {};
const dest = [];
let result: any[];
const data = [
{ code: "aa", name: "王二" },
{ code: "aa", name: "王二" },
{ code: "aa", name: "王二" },
{ code: "aa", name: "王二" },
];
data.forEach(item => {
if (!map[item.code]) {
dest.push({
code: item.code,
lst: [item]
});
map[item.code] = item;
} else {
dest.forEach(it => {
if (it.code === item.code) {
it.lst.push(item);
}
});
}
});
result = [...dest];
去重
//ES6
const dic = [1, 1, 3, 5];
const rlt = Array.from(new Set(dic));
//ES5
1.
const arr = [];
if (dic.length > 0) {
dic.forEach(item => {
if (arr.findIndex(it => it === item)) {
arr.push(item);
}
})
}
console.log(arr);
2.时间复杂度o(n)
function fn(arr) {
let obj = {};
arr.forEach((item) => {
obj[item] = '';//只保存最后出现的键为准,从而去重
})
return Object.keys(obj)
}
3.时间复杂度o(n*n)
function fn(arr) {
//第一次出现的的元素下标才等于下标
return arr.filter((item, index, arr) =>arr.indexOf(item) === index)
}
网友评论