将两个数组一一比较并使用开发函数创建新数组 javascript

Compare two arrays one by one and make new array using function developing javascript

我有两个数组:

colors1 = ['green', 
'', 
'red',
'',
'black'];

colors2 = ['purple',
yellow,
'red',
''];


console.log(result);
    [
    ['green', 'purple'],
    [null, 'yellow'],
    'black', null
    ];

我需要根据条件创建新数组 result

  1. result包含每个元素包含两个元素的数组;
  2. 第一个元素 = 来自 colors1 的颜色,第二个 = 来自 colors1 的颜色 colors2;
  3. 如果颜色相同则跳过它们(不是 包含在 result);
  4. 如果数组中没有颜色则代替 这个元素我们放 null
  5. 我们只需要使用功能 使用不可变对象编程。

我想我应该:

  1. 比较长度;
  2. 使biggest.reduce();

但不知道该怎么做。 提前谢谢你。

But have no idea how to do it

我认为这不完全正确,因为您能够准确描述应该发生的事情...您是否尝试过从 "regular" 循环开始而不首先担心 reduce 和不变性?

如果我将您的要求和问题转化为代码,这就是我得到的:

const colors1 = ['green', '', 'red', '', 'black'];
const colors2 = ['purple', 'yellow', 'red', '' ];

const colorPairs = (set1, set2) => {
  const biggest = set1.length >= set2.length ? set1 : set2;
  
  return biggest.reduce(
    (colors, _, i) => {
      const c1 = set1[i] || null;
      const c2 = set2[i] || null;
      
      if (c1 !== c2) colors.push([c1, c2]);
      
      return colors;
    }, []);
};

console.log(colorPairs(colors1, colors2))

现在,我很想知道您不理解此处使用的哪些概念。请在评论中让我知道...

I think I should: (1) compare length; (2) make biggest.reduce();

const biggest = set1.length >= set2.length ? set1 : set2;
return biggest.reduce(/* ... */, []);

first element = color from colors1, second one = color from colors2

const c1 = set1[i];
const c2 = set2[i];

if colors are the same then they are skipped (not included in result)

if (c1 !== c2) colors.push([c1, c2]);

if has no color in array then instead of this element we put null.

const c1 = set1[i] || null;
const c2 = set2[i] || null;
//                  ^-- "" or undefined is replaced by null

We need to use only functional programming with immutable objects.

每次 运行 colorPairs 我们 return 一个新数组并且不触及输入数组。如果您希望结果实际上是不可变的,我建议您查看 Immutable.js 之类的库并将结果转换为 List:

const result = List(colorPairs(colors1, colors2));