简体   繁体   English

从数组中删除不匹配的元素

[英]Remove non matching elements from array

So, I have two arrays and I want to remove all elements from array2 that's not included as a number in array1 (example arrays below will make it more clear). 因此,我有两个数组,我想从array2中删除所有未作为数字包含在array1中的元素(下面的示例数组将使其更加清楚)。

I guess a for loop and an if statement could do the trick, but I assume there's a more elegant solution for this, if someone has a suggestion? 我猜想for循环和if语句可以解决问题,但是如果有人提出建议,我认为有一个更优雅的解决方案?

var elemsToKeep = [1, 3, 5, 6, 8];

var arr[0] = 'foo1';
var arr[1] = 'foo2';    // remove
var arr[2] = 'foo3';
var arr[3] = 'foo4';    // remove
var arr[4] = 'foo5';
var arr[5] = 'foo6';
var arr[6] = 'foo7';    // remove
var arr[7] = 'foo8';
var arr[8] = 'foo9';    // remove
var arr[9] = 'foo10';   // remove

Instead of trying to remove the values you don't need, rather create a new array with only the values you need. 与其尝试删除不需要的值,不如创建仅包含所需值的新数组。 Hint: it involves a loop and Array.push . 提示:它涉及一个循环和Array.push

Perhaps a filter (first time I use one so I just popped off and made a jsfiddle.net ) 也许是一个过滤器 (第一次使用过滤器,所以我弹出并创建了jsfiddle.net

Note updated to remove any non-numeric char - that means 1foo2 will become 12 - let me know if that is not what you want, then a different regexp can be applied 注意已更新以删除任何非数字字符-这意味着1foo2将变为12-让我知道是否不是您想要的,然后可以应用其他正则表达式

var elemsToKeep = [1, 3, 5, 6, 8];

var arr=[];
arr[0] = 'one1';
arr[1] = 'two2';   // remove
arr[2] = 'three3';
arr[3] = 'four4';  // remove
arr[4] = 'five5';
arr[5] = 'six6';
arr[6] = 'seven7'; // remove
arr[7] = 'eight8';
arr[8] = 'nine9';  // remove
arr[9] = 'ten0';   // remove

function keep(element, index, array) {
  var num = parseInt(element.replace(/[^\d]/g,''),10); // any char!
  return elemsToKeep.indexOf(num) !=-1;
}

var filtered = arr.filter(keep);
alert(filtered)​

You could use Underscore's _reject function: 您可以使用Underscore的_reject函数:

var filtered = _reject(arr2, function(element, index) {
   return elementsToKeep.indexOf(index +1) == -1;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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