javascript - js/array : 比较 3 个数组并“转移”一个值
问题描述
我目前有三个这样的 js 数组:
let array1 = ['A', 'B', 'C'];
let array2 = ['D', 'E', 'F'];
let array3 = ['G', 'H', 'I'];
在一些用户从数组中删除值以将它们添加到其他数组的操作之后,实现这一点并获得如下输出的最佳方法(和逻辑)是什么:
array1 = ['B'];
array2 = ['D', 'E', 'F', 'A', 'I'];
array3 = ['G', 'H', 'C'];
一些精度,在开始时数组可能是空的:
let array1 = [];
let array2 = [];
然后,添加一个事件作为值:
array1 = ['A'];
array2 = [];
然后,将另一个事件添加为 value :
array1 = ['A', 'B'];
array2 = [];
然后,修改相同的事件:
array1 = ['A'];
array2 = ['B'];
然后,将另一个事件添加为 value :
array1 = ['A', 'C'];
array2 = ['B'];
...
最后的输出可能是(带有第三个数组):
array1 = ['C'];
array2 = ['B', 'D'];
array3 = ['E', 'A'];
解决方案
编辑:使它适合您的最后评论,并使用与您相同的示例。
let type1 = [];
let type2 = [];
let type3 = [];
function addOrEditChoice(user, array) {
// remove current user from all the other arrays
removeAlterEgos(user);
// ...and add him to the new one:
if (array === "type1") {
type1.push(user);
} else if (array === "type2") {
type2.push(user);
} else if (array === "type3") {
type3.push(user);
} else {
// (just a typo fallback)
console.log("Give a valid array-name!");
}
}
function removeAlterEgos(user) {
// type1.forEach((key, index) => {
// if (key === user) {
// type1.splice(index, 1);
// }
// });
// ...same but shorter:
type1 = type1.filter(key => {
return key !== user;
});
// ...and even shorter:
type2 = type2.filter(key => key !== user);
type3 = type3.filter(key => key !== user);
}
function printArrays() {
console.log("array1: ", type1);
console.log("array2: ", type2);
console.log("array3: ", type3);
console.log("");
}
// STEP 1
console.log("> User1 add his choice with type1:");
addOrEditChoice("user1", "type1");
printArrays();
// STEP 2
console.log("> User2 add his choice with type2:");
addOrEditChoice("user2", "type2");
printArrays();
// STEP 2
console.log("> User1 modify his choice with type2:");
addOrEditChoice("user1", "type2");
printArrays();
// STEP 2
console.log("> User3 add his choice with type1:");
addOrEditChoice("user3", "type1");
printArrays();
// STEP 2
console.log("> User3 modify his choice with type2:");
addOrEditChoice("user3", "type2");
printArrays();
推荐阅读
- python - 如何使用 Pyspark 在列表中获取唯一组合?
- javascript - Counting divs with specific classes before header tag with JavaScript/JQuery in HTML-doc
- javascript - REACT NATIVE FIRESTORE SUBCOLLECTION PROBLEM
- c# - 方法不改变外部变量 C#
- javascript - HTML SVG - load base64 string data to href of or any workaround
- react-native - React native - ScrollView 内的分页 SectionList
- forms - Trying to redirect user on valid contact form submission
- python - How do I fix WinError 126 for Pyenchant?
- javascript - ERROR : undefined is not an object (evaluation 'style.width')
- reactjs - 如何从对象数据中获取 React '@material-ui/data-grid' 的列和行