MoonEater916
MoonEater916

Reputation: 446

Javascript remove object from array using object variable

So I am trying to use arrays and for demonstration purposes I have condensed the code using points as examples. I want to create a point and push it to array and after doing stuff I want to remove the point from the array.

var PointArray = [];
function CreatePoint(X,Y){
    this.x=X;
    this.y=Y;
    PointArray.push(this);
}
function RemovePoint(PointObject){
     //????
}
var xPoint = CreatePoint(10,10);
//do stuff
RemovePoint(xPoint);

I was looking at the ‍Array.prototype manual and PointArray.Splice seems like a the closest but feels messy since it wants indexs. Anyone have a clean way remove objects from array to shove into function RemovePoint?

Upvotes: 0

Views: 71

Answers (2)

Puneet
Puneet

Reputation: 654

Why not use filter to remove elements from PointArray

var PointArray = [];
function CreatePoint(X,Y){
    this.x=X;
    this.y=Y;
    PointArray.push(this);
}
function RemovePoint(PointObject){
  PointArray = PointArray.filter(singlePoint=>!(singlePoint.x==PointObject.x && singlePoint.y==PointObject.y));
}
var xPoint = new CreatePoint(10,10);
var yPoint = new CreatePoint(20,20);
//do stuff
console.log(PointArray);
RemovePoint(xPoint);
console.log(PointArray);

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370639

To find the index of something in an array, use indexOf:

function RemovePoint(PointObject){
  const index = PointArray.indexOf(PointObject);
  PointArray.splice(index, 1); // remove one item at index "index"
}

But if you're doing something like this, you might consider using a Set instead, which might be more appropriate if you want a collection, but the index of each object doesn't actually matter - then, you could just call PointSet.delete(PointObject);:

const PointSet = new Set();
function CreatePoint(X,Y){
  this.x=X;
  this.y=Y;
  PointSet.add(this);
}
function RemovePoint(PointObject){
  PointSet.delete(PointObject);
}
console.log(PointSet.size);
const xPoint = new CreatePoint(10,10);
console.log(PointSet.size);
RemovePoint(xPoint);
console.log(PointSet.size);

As comment notes, make sure to use new when calling a constructor like CreatePoint.

Upvotes: 4

Related Questions