首页 > 解决方案 > 如何从 JavaScript 数组中删除元素?

问题描述

我想删除数组中的值,但下面的代码不起作用:

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;
 });

}

上面的这段代码不会{location: "stations1"}, {location: "stations2"}从航路点中删除,请问有什么建议吗?

标签: javascript

解决方案


这是一种方法:

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

同样的,但有解构的论点:

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

希望能帮助到你。


推荐阅读