首页 > 解决方案 > 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'];

标签: javascriptarraysnode.js

解决方案


编辑:使它适合您的最后评论,并使用与您相同的示例。

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();


推荐阅读