Home > OS >  remove duplicates from array in typescript when we have array.push
remove duplicates from array in typescript when we have array.push

Time:11-18

I have

let array1: any[] = [];
let array2: any[] = [];

Now I am pushing whole array2 to array1 but before pushing I need to check whether array2[1] and array2[4] already exists in array1 or not if exists skip else push.

 for (let count= 0; count < sheet.length; count  ) {
array2 = [sheet[count][0],sheet[count][1],sheet[count][2], sheet[count][3],sheet[count][4]];
// here need to put condition if array1 already has array2[0] and array2 [3] then don't push it to array1. 
array1.push(...[array2]); 
// in array1 I can see duplicate rows like that shouldn't happen 
// 0: 1,2,3,4,5
// 1: 1,2,3,4,5
}

CodePudding user response:

You can use Set to remove duplicates. Items in a Set have to be unique.

You can read more about it here

Here is how you can do it:

const uniqueArray = Array.from(new Set(array1.concat(array2)));

CodePudding user response:

First concatenate the two arrays, next filter out only the unique items:

var a = [1, 2, 3];
var b = [3, 4, 5, 6]
var c = a.concat(b)
var d = c.filter((item, pos) => c.indexOf(item) === pos)

console.log(d) // output: [1,2,3,4,5,6]
  • Related