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}]
2
  • Take a look at Lodash lodash.com Commented Sep 5, 2015 at 22:21
  • Your question is supposed to be about fixing what you have written, not asking to write the code for you. Commented Sep 5, 2015 at 22:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.