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?
-
Slice is how you do it unless you want to use a library.Dave Newton– Dave Newton2018年08月25日 03:52:20 +00:00Commented Aug 25, 2018 at 3:52
2 Answers 2
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.
3 Comments
CreatePoint increases the Set's size to 1, and then calling RemovePoint reduces the size to 0.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);