0

Scenario 1

An API that i call returns an array with duplicates.

var array1 = [{id:1, foo:23},{id:1, foo:24},{id:1, foo:22},{id:2, foo:26},{id:3, foo:26}]; //example

Question 1 -> how do I eliminate the duplicates to get a desired result of:

var array2 = [{id:1, foo:23 },{id:2, foo:26},{id:3, foo:26}];

Scenario 2

In my pagination i would call a new set of array

var array1 = [{id:2, foo:27},{id:2, foo:28},{id:3, foo:29},{id:4, foo:28},{id:5, foo:23}]; //example

i then do a foreach loop, to push it to array2.

var array2 = [{id:1, foo:23},{id:2, foo:27},{id:3, foo:27}];

angular.forEach(array1, function(a){
              array2.push(a)                           
         });

Question 2 -> How do i prevent an object in array1 that exists in array2 from getting pushed.

desired result:

var array2 = [{id:1, foo:23},{id:2, foo:27},{id:3, foo:27},{id:4, foo:28},{id:5, foo:23}]
teddybear123
  • 2,314
  • 6
  • 24
  • 38

1 Answers1

1

I suggest Lodash library (https://lodash.com), it simplifies life alot.

If you are willing to use Lodash it has uniq function (https://lodash.com/docs#uniq).

var myUniqObjectArray = _.uniq(array1, 'id');

Where array1 is the source array, id is the property based on which all objects are compared.

tiblu
  • 2,959
  • 1
  • 22
  • 22
  • I have another field that is not consistent, so i have to base it by the id. I edited my code please check thank you – teddybear123 Sep 05 '15 at 22:28
  • I'm not sure I understand. Even when changing your sample, the proposed solution returns the expected result. So, ``_.uniq(array1, 'id');`` will give the result ``[{id:1, foo:23 },{id:2, foo:26},{id:3, foo:26}];`` (array2). Maybe I get it wrong and new base data and expected result are in order. – tiblu Sep 05 '15 at 22:40