[英]How to remove elements from array other then x or y in javascript
I am trying to remove all the elements from the array other then x or y (if available)我正在尝试从数组中删除除 x 或 y 之外的所有元素(如果可用)
Example: Case 1:示例:案例 1:
let array = ['a','b','c','d','x','y']
So,in that case, other then x and y, I want to remove all the other elements.所以,在那种情况下,除了 x 和 y,我想删除所有其他元素。 output:
['x','y']
输出:
['x','y']
Case 2:案例2:
let array = ['a','b','c','d','x']
In this case, other then x, I want to remove all the other elements.在这种情况下,除了 x,我想删除所有其他元素。 output:
['x']
输出:
['x']
Case 3:案例3:
let array = ['a','b','c','d']
In this case, I want to remove all the elements.在这种情况下,我想删除所有元素。 output:
[ ]
输出:
[ ]
Couldn't find a better approach to go ahead with that.找不到更好的方法来继续进行。 Any help will be appreciated.
任何帮助将不胜感激。 THANK YOU :)
谢谢你 :)
Simply declare the allowed strings in inside an alone array and then use the filter
method on the array.只需在单独的数组中声明允许的字符串,然后在数组上使用
filter
方法。
const allowedStrings = ['x', 'y'];
let array = ['a','b','c','d','x','y'].filter(
item => allowedStrings.includes(item)
);`
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter来源: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
You can use Array.filter
and Array.includes
.您可以使用
Array.filter
和Array.includes
。
let array = ['a','b','c','d','x','y'].filter(item => ['x','y'].includes(item));
console.log(array);
您可以使用以下命令完成此操作:
array = array.filter(v => v==="x" || v==="y")
You can accomplish this with Array.prototype.filter()
and Array.prototype.includes
您可以使用
Array.prototype.filter()
和Array.prototype.includes
完成此操作
let array = ['a', 'b', 'c', 'd']; // create the array // filter out every letter not included in the given array console.log(array.filter((letter) => ['a', 'b'].includes(letter))); // you can also filter out every letter that *is* is the given array console.log(array.filter((letter) => !['a', 'b'].includes(letter)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.