zoukankan      html  css  js  c++  java
  • 多个数组对象合并去重

    一个数组对象去重

     1 var songs = [
     2  {name:"羽根",artist:"air"}, 
     3 {name:"羽根",artist:"air"}, 
     4 {name:"晴天",artist:"周杰伦"}, 
     5 {name:"晴天",artist:"周杰伦"}, 
     6 {artist:"周杰伦",name:"晴天"} 
     7 ];
     8 
     9 function unique(songs){ 
    10     let result = {}; 
    11     let finalResult=[]; 
    12     for(let i=0;i<songs.length;i++){ 
    13      result[songs[i].name]=songs[i];//因为songs[i].name不能重复,达到去重效果,且这里必须知晓"name"或是其他键名
    14  } 
    15  //console.log(result);{"羽根":{name:"羽根",artist:"air"},"晴天":{name:"晴天",artist:"周杰伦"}} //现在result内部都是不重复的对象了,只需要将其键值取出来转为数组即可
    16     for(item in result){ 
    17      finalResult.push(result[item]); 
    18     } 
    19 //console.log(finalResult);[{name:"羽根",artist:"air"},{name:"晴天",artist:"周杰伦"}]
    20  return finalResult; 
    21 } 
    22 console.log(unique(songs));

    多个数组对象去重

    var songs = [
     {name:"羽根",artist:"air"}, 
    {name:"晴天",artist:"周杰伦"}, 
    {artist:"周杰伦",name:"晴天"} 
    ];
    
    var arr = [
    {name:"羽根",artist:"air"}, 
    {name:"晴天",artist:"周杰伦"}, 
    ]
    
    for (let i = 0; i < arr.length; i++) {
        songs.push(arr[i])
    }
    
    console.log(songs);
    
    
    function unique(songs){ 
        let result = {}; 
        let finalResult=[]; 
        for(let i=0;i<songs.length;i++){ 
         result[songs[i].name]=songs[i];//因为songs[i].name不能重复,达到去重效果,且这里必须知晓"name"或是其他键名
     } 
     //console.log(result);{"羽根":{name:"羽根",artist:"air"},"晴天":{name:"晴天",artist:"周杰伦"}} //现在result内部都是不重复的对象了,只需要将其键值取出来转为数组即可
        for(item in result){ 
         finalResult.push(result[item]); 
        } 
    //console.log(finalResult);[{name:"羽根",artist:"air"},{name:"晴天",artist:"周杰伦"}]
     return finalResult; 
    } 
    console.log(unique(songs));

  • 相关阅读:
    [POI2009]SLOElephants
    java回顾之集合概述
    java回顾之初始化
    java回顾之包装类
    java回顾之Set
    action,category
    java回顾之继承 二
    java回顾之TreeSet
    java回顾之final
    java回顾之继承
  • 原文地址:https://www.cnblogs.com/mxyr/p/9238287.html
Copyright © 2011-2022 走看看