How to identify repeated instances?

0

function Cell(){
  
  this.id = null;  
  this.name = "";
  
}
var x = [1,4,5,9,17,25,254,4];
var i = 0;
var l = x.length;
for(;i<l;i++) {
  
  var b = new Cell();
  b.id = x[i];

 
  console.log(b.id);
}

I have a constructor Cell() , an array called x (with identifiers for Cell), and a cycle for that creates instances of the constructor with property id , assigned from the values of the array x .

How can I check if there is 'this.id' repeated ? since for each property 'this.id' I want to make a certain funcion but if the property 'this.id' is repeated em> (in this case the id 4 is repeated), the function only applies to the last of its repetitions, that is to the last 4

I can not solve the problem by modifying the array and always with the same variable name

Something similar to doing it with an array, but now with the intancias

Example:

var a = [1,2,3,4,5,6,7,1,1]
var b = new Set()
a.reverse().forEach(x => b.add(x))
c = Array.from(b).reverse()

console.log(c);
    
asked by Eduardo Sebastian 22.07.2017 в 01:04
source

1 answer

1

At the moment you set b.id = x[i] you can check if it is the last occurrence of the value x[i] within the array.

To solve that you can use Array.prototype.lastIndexOf () , since this function returns the index of the last occurrence of the value, being able then to use that index to verify if it coincides with your iteration variable i .

If you agree you know that you are positioned in the last occurrence, therefore you would invoke the function you mention.

If it does not match it can mean that there is a later value ( index > i ) or that there is a previous value and the id was used ( index < i ).

function Cell(){
  this.id = null;  
  this.name = "";
}

var x = [1,4,5,9,17,25,254,4,88,17];
var i = 0;
var l = x.length;

for(;i<l;i++) {
  var b = new Cell();
  var index = x.lastIndexOf(x[i]);
  b.id = x[i];
  if(index !== i){
      console.log(b.id+ " Fue utilizado previamente o no es la ultima ocurrencia");
  }else{
      console.log(b.id+ " Es la ultima ocurrencia, invocar funcion..");
  }
 }
 
    
answered by 22.07.2017 / 01:30
source