简体   繁体   中英

How to remove an element from JavaScript array?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM