1

I am trying to remove duplicates in an array in JavaScript. The given array being

array = [1,1,1,1,1,1,1,1,1,,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,1,1,1,1,1,2,2,2,2,2,2,2,2]

resultant_array = [1,2,3,1,2]

Here the second 1 is not considered as a duplicate

OR

array = [1,1,1,1,1,1,1,1,1,1,1,1]

resultant_array = [1]

any ideas how i can do this

Mahima
  • 65
  • 1
  • 8

3 Answers3

1

You can use reduce like this:

var array = [1,1,1,1,1,1,1,1,1,,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,1,1,1,1,1,2,2,2,2,2,2,22];

var result = array.reduce(function(r, e) {
  if(r[r.length - 1] != e) // if the last element in the result is not equal to this item, then push it (note: if r is empty then r[-1] will be undefined so the item will be pushed as any number is != undefined)
    r.push(e);
  return r;
}, []);

console.log(result);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1
var arr = [1,1,2,2,3,3];
var obj = {};
for(var i in arr) {
   obj[arr[i]] = true;
}
var result = [];
for(var i in obj) {
   result.push(i);
}

I set the keys of the object as the value of the array and there can't be multiple keys with the same value. Then I took all the keys and put it in the result.

ave4496
  • 2,950
  • 3
  • 21
  • 48
  • this will give me [1,2,3] in all cases ...even if i pass [1,1,2,2,3,3,1,1,2,2,3,3].. I need [1,2,3,1,2,3] in that case – Mahima Feb 20 '17 at 22:23
  • This may not have answered the OP's question but it certainly did answer mine. Thank you! – I0_ol Oct 16 '17 at 11:51
1

You could check the predecessor with Array#reduce

var array = [1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2],
    result = array.reduce(function (r, a) {
        return r[r.length - 1] === a ? r : r.concat(a);
    }, []);
    
console.log(result);

Or use Array#filter and an object for the last value.

var array = [1, 1, 1, 1, 1, 1, 1, 1, 1, , 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2],
    result = array.filter(function (a, i, aa) {
        return this.last !== a && (this.last = a, true);
    }, { last: undefined });
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392