-1

I want to delete values inside an array, but my code below doesn't work:

stations=['stations1','stations2']
 wayPoints=[{location: "stations1"},{location: "stations2"},{location: "stations3"},{location: "stations4"}]
deletStations(){

let result=[];

this.stations.forEach(index1 => rest.push(this.arrayRemove(this.wayPoints,index1)) );

}

arrayRemove(arr, value) {

 return arr.filter(function(ele){
     return ele != value;
 });

}

This code above doesn't remove the {location: "stations1"}, {location: "stations2"} from wayPoints, any suggestions please?

leonheess
  • 16,068
  • 14
  • 77
  • 112
Java user
  • 261
  • 3
  • 18
  • 7
    `Array.prototype.filter` doesn't mutate the input array, it returns a new array. It will not overwrite `wayPoints` unless you manually set the value. – nbokmans Jan 31 '20 at 13:44
  • Does this answer your question? [Deleting array elements in JavaScript - delete vs splice](https://stackoverflow.com/questions/500606/deleting-array-elements-in-javascript-delete-vs-splice) – Wendelin Jan 31 '20 at 13:44
  • @Wendelin I tried that, it doesnt work either – Java user Jan 31 '20 at 13:47
  • nbokmans is there a solution to overwrite waypoints – Java user Jan 31 '20 at 13:48
  • @Javauser manually assign the result of the `arrayRemove` call to `waypoints`. – nbokmans Jan 31 '20 at 13:49
  • the problem is in the result of arrayRemove, it doesnt return the correcte values – Java user Jan 31 '20 at 13:50
  • `arrayRemove` is testing for reference equality (`ele != value`) You need to check whether the property matches (`ele.location != 'value'`). But as the answer from sebaLinares show, there are better ways of doing this. – Scott Sauyet Jan 31 '20 at 14:06

1 Answers1

0

Here is one way of doing it:

const secondWayOfDoingIt = wayPoints.filter(
  element => !stations.includes(element.location)
);

And the same but with destructured argument:

const firstWayOfDoingIt = wayPoints.filter(
  ({ location }) => !stations.includes(location)
);

Hope it helps.

sebaLinares
  • 485
  • 5
  • 17