Several methods of deduplication of JavaScript array objects

The data to be filtered, remove the repeated city data in arr (the arr used in the following method are all this set of data)

var arr = [
  {
    
    id: 1,city: '南京'},
  {
    
    id: 2,city: '南京'}, 
  {
    
    id: 3,city: '杭州'}, 
  {
    
    id: 4,city: '广州'}
];

1. Object method: The reduce method of the array
does not support this method below ie9.
Portal: Detailed explanation of the reduce method

var obj = {
    
    };

var newArr = arr.reduce((prev,cur)=>{
    
    
  obj[cur.city] ? '':obj[cur.city] = true && prev.push(cur);
  return prev
},[]); //  [{id: 1,city: '南京'},{id: 3,city: '杭州'},{id: 4,city: '广州'}]  

2. Bubble sort

for (var i = 0; i < arr.length - 1; i++) {
    
    
  for (var j = i + 1; j < arr.length; j++) {
    
    
    console.log(i,j)
    if (arr[i].city == arr[j].city) {
    
    
      arr.splice(j, 1); 
      j--; // 因为数组长度减小1,所以直接 j++ 会漏掉一个元素,所以要 j--
    }
  }
}

console.log(arr); //  [{id: 1,city: '南京'},{id: 3,city: '杭州'},{id: 4,city: '广州'}] 

3. Double loop

var newArr = [];

arr.forEach((item) => {
    
    
  var check = newArr.every((b) => {
    
    
    return item.city !== b.city;
  })
  check ? newArr.push(item) : '';
})

console.log(newArr); //  [{id: 1,city: '南京'},{id: 3,city: '杭州'},{id: 4,city: '广州'}]  

4. ES6 Map Object
Portal: Detailed Explanation of Map Object

let formatArr = () => {
    
    
  let map = new Map();
  for (let item of arr) {
    
    
    if (!map.has(item.city)) {
    
    
      map.set(item.city, item);
    }
  }
  return [...map.values()];
}

let newArr = formatArr(); //  [{id: 1,city: '南京'},{id: 3,city: '杭州'},{id: 4,city: '广州'}]  

Guess you like

Origin blog.csdn.net/ZYS10000/article/details/109955135