如何从JS中的数组中删除一个子集?

时间:2019-02-10 16:29:00

标签: javascript arrays

假设我有一个数组,例如:[1, 1, 2, 2, 3, 3, 4, 5]
我想删除元素数组[1, 2, 3, 4, 5]
所以最后我想留下[1, 2, 3]

我尝试使用下面的方法,但是它从主数组中删除了元素的所有副本。

myArray = myArray.filter( function( el ) {
  return !toRemove.includes( el );
} );

4 个答案:

答案 0 :(得分:1)

您可以获得print("choose a die: \n 1 = d4 \n 2 = d6 \n 3 = d8 \n 4 = d10 \n 5 = d12 \n 6 = d20 \n 7 = d100 \n or 0 to quit program") u_input = int(input()) while u_input != 0: if u_input == 1: print("rolled a: [", random.randrange(1, 5), "] on a d4") u_input = int(input()) elif u_input == 2: print("rolled a: [", random.randrange(1, 7), "] on a d6") u_input = int(input()) elif u_input == 3: print("rolled a: [", random.randrange(1, 9), "] on a d8") u_input = int(input()) elif u_input == 4: print("rolled a: [", random.randrange(1, 11), "] on a d10") u_input = int(input()) elif u_input == 5: print("rolled a: [", random.randrange(1, 13), "] on a d12") u_input = int(input()) elif u_input == 6: print("rolled a: [", random.randrange(1, 21), "] on a d20") u_input = int(input()) elif u_input == 7: print("rolled a: [", random.randrange(1, 101), "] on a d100") u_input = int(input()) 并通过检查计数来计数值并进行过滤,并在发现计数时递减计数。

Map

答案 1 :(得分:1)

这是使用filterindexOfsplice的一种方法。

const input = [1, 1, 2, 2, 3, 3, 4, 5];

function removeSubset(arr, subset) {
  const exclude = [...subset];
  return arr.filter(x => {
    const idx = exclude.indexOf(x);
    if (idx >= 0) {
      exclude.splice(idx, 1);
      return false;
    }
    return true;
  });
}

console.log(removeSubset(input, [1, 2, 3, 4, 5]));

答案 2 :(得分:0)

您可以使用FilterShitfSort

Column

答案 3 :(得分:0)

一种解决方案是在要删除的元素数组上循环,并针对每个元素删除在输入数组中找到的第一个元素:

^

如果您仍要使用过滤器,则可以使用要删除的项目作为过滤器的const input = [1, 1, 2, 2, 3, 3, 4, 5]; const removeItems = (input, items) => { // Make a copy, to not mutate the input. let clonedInput = input.slice(); // Search and remove items. items.forEach(x => { let i = clonedInput.findIndex(y => y === x); if (i >= 0) clonedInput.splice(i, 1); }); return clonedInput; } console.log(removeItems(input, [1,2,3,4,5])); console.log(removeItems(input, [1,2])); console.log(removeItems(input, [1,99,44,5]));参数,如下所示:

this