user4870812
user4870812

Reputation:

How to get an array with unique values using AngularJS

I have an array with duplicated items. How can I get an array with unique items?

a= [{id: "1", campus: "c1"}, {id: "1", campus: "c1"}, {id: "2", campus: "c2"}, {id: "2", campus: "c2"}]

I want result with unique objects

a= [{id: "1", campus: "c1"}, {id: "2", campus: "c2"}]

Upvotes: 1

Views: 15829

Answers (3)

brewsky
brewsky

Reputation: 617

Angular jqLite implementation does not contain the $.filter function.

You have to provide your own implementation. You can do something like:

function getUniqueArray(array){
  var result = [];
  for(var x = 0; x < array.length; x++){
  if(result.indexOf(array[x]) == -1)
        result.push(array[x]);
  }
  return result;
}

Upvotes: 1

Tushar
Tushar

Reputation: 87203

You can use Array#filter as follow:

var arr = [{
    id: "1",
    campus: "c1"
}, {
    id: "1",
    campus: "c1"
}, {
    id: "2",
    campus: "c2"
}, {
    id: "2",
    campus: "c2"
}];

// Keep an array of elements whose id is added in filtered array
var elementId = [];

var newArr = arr.filter(el => {
    if (elementId.indexOf(el.id) === -1) {
        // If not present in array, then add it
        elementId.push(el.id);
        return true;
    } else {
        // Already present in array, don't add it
        return false;
    }
});

console.log(newArr);
document.getElementById('result').innerHTML = JSON.stringify(newArr, 0, 4);
<pre id="result"></pre>


Based on OP's comment

Please suggest best way with respect to performance..

If you're okay with underscore/lodash

You can use _.uniqWith

_.uniqWith(arr, _.isEqual);

var arr = [{
    id: "1",
    campus: "c1"
}, {
    id: "1",
    campus: "c1"
}, {
    id: "2",
    campus: "c2"
}, {
    id: "2",
    campus: "c2"
}];

var newArr = _.uniqWith(arr, _.isEqual);
console.log(newArr);
document.getElementById('result').innerHTML = JSON.stringify(newArr, 0, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.1/lodash.js"></script>
<pre id="result"></pre>

You can also use _.uniqBy

_.uniqBy(arr, 'id');

var arr = [{
    id: "1",
    campus: "c1"
}, {
    id: "1",
    campus: "c1"
}, {
    id: "2",
    campus: "c2"
}, {
    id: "2",
    campus: "c2"
}];

var newArr = _.uniqBy(arr, 'id');
console.log(newArr);
document.getElementById('result').innerHTML = JSON.stringify(newArr, 0, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.0.1/lodash.js"></script>
<pre id="result"></pre>

Upvotes: 5

AshBringer
AshBringer

Reputation: 2673

You can use unique from AngularUI

<li ng-repeat="x in myArr | unique:id">
  {{ x.campus }}
</li>

DEMO

Upvotes: 1

Related Questions