如何从数组中删除哪些元素是另一个数组的元素?

时间:2019-05-19 13:37:40

标签: javascript arrays

我有两个数组,其值分别是:

Digit your guess between 1 and 9
4
You have guessed the correct number
Digit your guess between 1 and 9
2
You have guessed to low
Digit your guess between 1 and 9
6
You have guessed to high
Digit your guess between 1 and 9
8
You have guessed to high
Digit your guess between 1 and 9
exit
(3, 1)

我想要这个数组。

const allValues = ["111", "111", "111", "222", "111", "222"]

const removingValues = ["111", "111", "222"]

我必须尝试const remaningValues = ["111", "222", "111"] ,但是它给出了空数组。如何以简单的方式做到这一点?

第一个数组包括_.difference(allValues, removingValues)"111" : 4 times 从此数组中删除的值为"222" : 2 times "111" : 2 times 其余值应为:"222" : 1 times"111" : 4-2 = 2

3 个答案:

答案 0 :(得分:2)

您可以使用此功能:

const allValues = ["111", "111", "111", "222", "111", "222"];
const removingValues = ["111", "111", "222"];

const result = allValues.filter(s => {
    let i = removingValues.indexOf(s);
    return i > -1 && removingValues.splice(i, 1);
});

console.log(result);

上面的时间复杂度为 O(n²),因此,如果您使用大型数组,最好创建某种哈希,例如使用{{1} },这会带来 O(n)时间复杂度:

Map

答案 1 :(得分:1)

您期望的剩余值的顺序对我来说毫无意义。如果您对['111', '111', '222'](而不是['111', '222', '111'])感到满意,那么可以通过以下简单代码来做到这一点:

const without = (i, xs) => i > -1 ? xs.slice(0, i).concat(xs.slice(i + 1)) : xs

const removeAll = (all, rems, idx = all .indexOf (rems[0])) => rems .length
  ? removeAll (without (idx, all), rems .slice(1))
  : all
  
const allValues = ["111", "111", "111", "222", "111", "222"];
const removingValues = ["111", "333", "111", "222"];

console .log (
  removeAll (allValues, removingValues)
)

辅助函数without仅返回不包含给定索引的旧数组的副本。

removeAll是要删除的内容的简单递归。如果为空,则返回其余列表。否则,我们将从列表中删除与要删除的第一个元素匹配的第一个索引,并将该索引和其余要匹配的项传递回removeAll

答案 2 :(得分:1)

您可以使用Array.reduceArray.spliceArray.indexOf这样非常简洁地完成此操作:

<form>
<section>
<div class="command">
<p>Insert_</p>
</div>
<div class="input">
<p><input type="text"></p>
</div>
</section>
</form>

想法是从要删除的值开始,并在Array.reduce中将const vals = ["111", "111", "111", "222", "111", "222"] const rms = ["111", "111", "222"] let r = rms.reduce((r,c) => (r.splice(r.indexOf(c), 1) && r), [...vals]) console.log(r)的实际副本作为累加器的起始值。然后在reduce内部,只需通过allValues

删除与indexOf匹配的值

Array.splice的副本是为了避免我们vals原始数组。如果您不关心变异,则可以:

mutate