How to get distinct values from an array of objects in JavaScript?

前端 未结 30 2652
执笔经年
执笔经年 2020-11-22 05:29

Assuming I have the following:

var array = 
    [
        {\"name\":\"Joe\", \"age\":17}, 
        {\"name\":\"Bob\", \"age\":17}, 
        {\"name\":\"Carl\         


        
相关标签:
30条回答
  • 2020-11-22 05:58

    I know my code is little length and little time complexity but it's understandable so I tried this way.

    I'm trying to develop prototype based function here and code also change.

    Here,Distinct is my own prototype function.

    <script>
      var array = [{
          "name": "Joe",
          "age": 17
        },
        {
          "name": "Bob",
          "age": 17
        },
        {
          "name": "Carl",
          "age": 35
        }
      ]
    
      Array.prototype.Distinct = () => {
        var output = [];
        for (let i = 0; i < array.length; i++) {
          let flag = true;
          for (let j = 0; j < output.length; j++) {
            if (array[i].age == output[j]) {
              flag = false;
              break;
            }
          }
          if (flag)
            output.push(array[i].age);
        }
        return output;
      }
      //Distinct is my own function
      console.log(array.Distinct());
    </script>

    0 讨论(0)
  • 2020-11-22 05:59

    const x = [
      {"id":"93","name":"CVAM_NGP_KW"},
      {"id":"94","name":"CVAM_NGP_PB"},
      {"id":"93","name":"CVAM_NGP_KW"},
      {"id":"94","name":"CVAM_NGP_PB"}
    ].reduce(
      (accumulator, current) => accumulator.some(x => x.id === current.id)? accumulator: [...accumulator, current ], []
    )
    
    console.log(x)
    
    /* output 
    [ 
      { id: '93', name: 'CVAM_NGP_KW' },
      { id: '94', name: 'CVAM_NGP_PB' } 
    ]
    */

    0 讨论(0)
  • 2020-11-22 06:00

    If you have Array.prototype.includes or are willing to polyfill it, this works:

    var ages = []; array.forEach(function(x) { if (!ages.includes(x.age)) ages.push(x.age); });
    
    0 讨论(0)
  • 2020-11-22 06:02

    using lodash

    var array = [
        { "name": "Joe", "age": 17 },
        { "name": "Bob", "age": 17 },
        { "name": "Carl", "age": 35 }
    ];
    _.chain(array).pluck('age').unique().value();
    > [17, 35]
    
    0 讨论(0)
  • 2020-11-22 06:03

    i think you are looking for groupBy function (using Lodash)

    _personsList = [{"name":"Joe", "age":17}, 
                    {"name":"Bob", "age":17}, 
                    {"name":"Carl", "age": 35}];
    _uniqAgeList = _.groupBy(_personsList,"age");
    _uniqAges = Object.keys(_uniqAgeList);
    

    produces result:

    17,35
    

    jsFiddle demo:http://jsfiddle.net/4J2SX/201/

    0 讨论(0)
  • 2020-11-22 06:04

    This is how you would solve this using new Set via ES6 for Typescript as of August 25th, 2017

    Array.from(new Set(yourArray.map((item: any) => item.id)))
    
    0 讨论(0)
提交回复
热议问题