Max Solid
Max Solid

Reputation: 1263

Angular2 using .filter() to get index and object from array?

Is there any way to make the following code simpler?

let objectModified = this.objectsModified.filter(objectModified => {
  if(objectModified.index === this.objectCurrent.index) {
    return objectModified;
  }
})[0]; /*[0] because there is no way the could be .length > 1 */

if(objectModified) {
  let index = this.objectsModified.indexOf(objectModified);
  this.objectsModified[index] = "something";
}

else {
  this.objectsModified.push("something");
}

It seems to me that there must be a smarter, more readable solution. But I can't figure it out.

Upvotes: 0

Views: 8352

Answers (1)

cartant
cartant

Reputation: 58410

Using findIndex would simplify things:

let objectModifiedIndex = this.objectsModified.findIndex(
  objectModified => objectModified.index === this.objectCurrent.index
);
if (objectModifiedIndex !== -1) {
  this.objectsModified[objectModifiedIndex] = "something";
} else {
  this.objectsModified.push("something");
}

Upvotes: 4

Related Questions