case one
Requirement: An 'array object', according to the 'id' attribute of the object to deduplicate.
If the two objects 'id' are equal, 'deduplication' will be performed
const dataArr = [
{
id: 1,
name: '名称1'
},
{
id: 2,
name: '名称2'
},
{
id: 2,
name: '名称3'
},
{
id: 2,
name: '名称4'
},
{
id: 3,
name: '名称5'
},
{
id: 4,
name: '名称6'
},
{
id: 5,
name: '名称7'
}
]
First use map () to get all the id values
const a = dataArr.map(item => {
return item.id
})
console.log(a) // ['a', 'b', 'b', 'b', 'c', 'b', 'd']
Then use filter () to filter Use indexOf() to get the subscript of each item in the a array (repeatedly return the subscript encountered for the first time) is equal to the subscript of the unfiltered array and return all the arrays that meet the conditions
const b = dataArr.filter((item, index) => {
return a.indexOf(item.id) === index
})
console.log(b)
The obtained b is the filtered array
[
{ id: 'a', name: '名称1' },
{ id: 'b', name: '名称2' },
{ id: 'c', name: '名称5' },
{ id: 'd', name: '名称7' }
]
Case two
Requirement: An 'array object', according to the 'id' attribute and the 'name' attribute to deduplicate, that is to say, the two objects are congruent.
If the two objects 'id' and 'name' are equal, 'deduplication' will be performed
const dataArr = [
{
id: 1,
name: '名称1'
},
{
id: 2,
name: '名称2'
},
{
id: 2,
name: '名称2'
},
{
id: 2,
name: '名称3'
},
{
id: 3,
name: '名称4'
},
{
id: 4,
name: '名称4'
},
{
id: 5,
name: '名称5'
}
]
const arr1 = []
const arr2 = []
for (let i = 0; i < dataArr.length; i++) {
if (!(arr1.includes(dataArr[i].id + '-' + dataArr[i].name))) { // 1-名称1 / 2-名称2 等等。。。
// 数组中没有就往里添加
arr1.push(dataArr[i].id + '-' + dataArr[i].name)
arr2.push({
id: dataArr[i].id,
name: dataArr[i].name
})
}
}
// console.log(arr2)
// [
// { "id": 1, "name": "名称1" },
// { "id": 2, "name": "名称2" },
// { "id": 2, "name": "名称3" },
// { "id": 3, "name": "名称4" },
// { "id": 4, "name": "名称4" },
// { "id": 5, "name": "名称5" }
// ]