how to get last records of unique usernames from an array in java script

前端 未结 3 1942
余生分开走
余生分开走 2021-01-29 10:46

I have an Array of Objects Like:

[ 
 { id: 8, username: \'peter\' ,weight:80,date:\'2019-10-14\'},
 { id: 1, username: \'harry\' ,weight:80,date:\'2019-01-01\'},         


        
相关标签:
3条回答
  • 2021-01-29 10:58

    Check the array from end for current object username and previous object username. If they are same break the loop, else push in the array.

    const input =  [ 
          { id: 1, username: 'harry' ,weight:80,date:'2019-01-01'},
          { id: 2, username: 'harry' ,weight:84,date:'2019-02-21'},
          { id: 3, username: 'john' ,weight:80,date:'2019-03-11'},
          { id: 4, username: 'peter' ,weight:80,date:'2019-08-06'},
          { id: 5, username: 'peter' ,weight:80,date:'2019-06-11'},
          { id: 6, username: 'harry' ,weight:90,date:'2019-04-03'},
          { id: 7, username: 'john' ,weight:80,date:'2019-05-25'},
          { id: 8, username: 'peter' ,weight:80,date:'2019-10-14'},
    ];
    
    const output = [];
    
    for(let i = input.length-1; i > 0; i--) {
          if(input[i].username === input[i-1].username) {
              break;
          }
          output.push(input[i]);
    }
    
    console.log(output.sort((a, b) => a.date.localeCompare(b.date.localeCompare)));

    0 讨论(0)
  • 2021-01-29 11:05

    You could take a Map and get the values.

    var array = [{ id: 1, username: 'harry', weight: 80, date: '2019-01-01' }, { id: 2, username: 'harry', weight: 84, date: '2019-02-21' }, { id: 3, username: 'john', weight: 80, date: '2019-03-11' }, { id: 4, username: 'peter', weight: 80, date: '2019-08-06' }, { id: 5, username: 'peter', weight: 80, date: '2019-06-11' }, { id: 6, username: 'harry', weight: 90, date: '2019-04-03' }, { id: 7, username: 'john', weight: 80, date: '2019-05-25' }, { id: 8, username: 'peter', weight: 80, date: '2019-10-14' }],
        result = Array.from(new Map(array.map(o => [o.username, o])).values());
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
  • 2021-01-29 11:13

    Maps and Sets inherently only hold unique values. You can use this as following:

    var myMap = [ 
     { id: 1, username: 'harry' ,weight:80,date:'2019-01-01'},
     { id: 2, username: 'harry' ,weight:84,date:'2019-02-21'},
     { id: 3, username: 'john' ,weight:80,date:'2019-03-11'},
     { id: 4, username: 'peter' ,weight:80,date:'2019-08-06'},
     { id: 5, username: 'peter' ,weight:80,date:'2019-06-11'},
     { id: 6, username: 'harry' ,weight:90,date:'2019-04-03'},
     { id: 7, username: 'john' ,weight:80,date:'2019-05-25'},
     { id: 8, username: 'peter' ,weight:80,date:'2019-10-14'},
    ]
    
    var result = {};
    for(i = 0; i < myMap.length; i++){
    	result[myMap[i]['username']] = myMap[i];
    }
    
    console.log(Object.values(result));

    0 讨论(0)
提交回复
热议问题