Dharmesh
Dharmesh

Reputation: 6003

Angular : how to stop duplicate item push in array?

Here data console and this data push in duplicatePushArray but it once pushed I dont want to push again but if I push again i want to show same message second time also.

Ex. first time I push 2.jpg,3.jpg now again I push 2.jpg,3.jpg so it shows message like this 2.jpg,3.jpg value is already pushed please change this values now again I push 2.jpg,3.jpg so it shows message like this 2.jpg,3.jpg,2.jpg,3.jpg value is already pushed please change this values but i want to show message like this 2.jpg,3.jpg value is already pushed please change this values

console.log(data); // (2) [{…}, {…}]0: {imageName: "2.jpg"}1: {imageName: "3.jpg"}
duplicatePushArray : any[] = [];
constructor(private snackBar : MatSnackBar) {}      

for(var i = 0; i < data.length ; i++){
  if(this.duplicatePushArray.indexOf(data[i].imageName)) {
    this.duplicatePushArray.push(data[i].imageName);
    this.snackBar.open(this.duplicatePushArray+' '+ 'value is already pushed please change this values', '',{
      duration: 2000
    })
  }
}

Upvotes: 1

Views: 6995

Answers (1)

sridhar
sridhar

Reputation: 622

const data = [1,2,3,4,5,6,7,1,2,3,4,1,2];
let duplicatePushArray = [];
for(let i = 0; i < data.length ; i++){
  if(duplicatePushArray.indexOf(data[i]) === -1) {
    duplicatePushArray.push(data[i]);
  } else {
    console.log(`${data[i]} is already pushed into array`);
  }
}

console.log('Final Array: ', duplicatePushArray)

Upvotes: 3

Related Questions