push only unique elements in an array

后端 未结 6 1449
-上瘾入骨i
-上瘾入骨i 2021-01-19 14:25

I have array object(x) that stores json (key,value) objects. I need to make sure that x only takes json object with unique key. Below, example \'id\' is the key, so i don\'t

6条回答
  •  没有蜡笔的小新
    2021-01-19 15:04

    This is how I would do it in pure javascript.

    var x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}];
    
    function unique(arr, comparator) {
      var uniqueArr = [];
      for (var i in arr) {
        var found = false;
        for (var j in uniqueArr) {
          if (comparator instanceof Function) {
            if (comparator.call(null, arr[i], uniqueArr[j])) {
              found = true;
              break;
            }
          } else {
            if (arr[i] == uniqueArr[j]) {
              found = true;
              break;
            }
          }
        }
        if (!found) {
          uniqueArr.push(arr[i]);
        }
      }
      return uniqueArr;
    };
    
    u = unique(x, function(a,b){ return a.id == b.id; });
    console.log(u);
    
    y = [ 1,1,2,3,4,5,5,6,1];
    console.log(unique(y));

提交回复
热议问题