我有:
const currentState = ['Godwin', 'Hadrada', 'Timujin', 'LaGrandBatard']
const selection = ['Atila', 'Godwin']
从第一个数组中删除值(如果它已经包含选择数组中的一个值)并如果尚未添加该值的最佳方法是什么?包含其中一个值?
只是为了更清楚地表明最终结果应该是:
newArray = ['Hadrada', 'Timujin', 'LaGrandBatard', 'Atila']
答案 0 :(得分:1)
const currentState = ['Godwin', 'Hadrada', 'Timujin', 'LaGrandBatard']
const selection = ['Atila', 'Godwin']
let foo = {}
currentState.forEach(bar => {
foo[bar] = true
})
selection.forEach(bar => {
if (foo[bar]) {
delete foo[bar]
} else {
foo[bar] = true
}
})
const results = Object.keys(foo)
console.log(results)
答案 1 :(得分:1)
ES6在JavaScript中合并两个数组并删除重复项
const currentState = ['Godwin', 'Hadrada', 'Timujin', 'LaGrandBatard']
const selection = ['Atila', 'EvaBrown']
const array3 = [...new Set([...currentState ,...selection])];
console.log(array3);
答案 2 :(得分:1)
有很多解决此问题的方法。这是使用reduce
+ indexOf
的一个:
const currentState = ['Godwin', 'Hadrada', 'Timujin', 'LaGrandBatard'];
const selection = ['Atila', 'Godwin'];
const newState = selection.reduce((a, s) => {
var i = a.indexOf(s);
if (i === -1) {
a.push(s);
} else {
a.splice(i, 1);
}
return a;
}, [...currentState]);
console.log(...newState);
要就地修改集合,只需使用currentState
而不是[...currentState]
这是使用reduce
和Set
的另一个更简洁的解决方案:
const currentState = ['Godwin', 'Hadrada', 'Timujin', 'LaGrandBatard'];
const selection = ['Atila', 'Godwin'];
const newState = Array.from(selection.reduce(
(a, s) => (a.has(s) ? a.delete(s) : a.add(s), a),
new Set(currentState)));
console.log(...newState);