【问题标题】:Using only `.reduce()` to swap 2 elements in the array in JavaScript?仅使用`.reduce()`在JavaScript中交换数组中的2个元素?
【发布时间】:2019-07-10 13:47:47
【问题描述】:

我想知道是否可以在 JavaScript 中仅使用 .reduce 来完成交换元素。如果没有,函数式编程领域还应该使用什么?

这不适用于对数组进行排序。我想使用.reduce 找到数组元素的所有排列,这需要按照this 方法进行交换步骤。

【问题讨论】:

  • 你有数组的例子吗?为什么要使用reduce?
  • 您通常使用.sort() 更改数组元素的顺序。
  • 你想创建一个新的数组实例,交换两个值,还是只是(可变地)交换到数组的元素?

标签: javascript functional-programming reduce


【解决方案1】:

您可以采用一个函数,该函数接受一个数组和两个索引并使用 destructuring assignment

const swap = (array, i, j) => [array[i], array[j]] = [array[j], array[i]];

var array = [1, 2, 3];

swap(array, 0, 1)
console.log(array);

一个带有 reduce 的版本,它采用一组索引并从头到尾交换所有对。

const
    swap = (array, ...indices) => 
        indices.reduce((a, b) => ([array[a], array[b]] = [array[b], array[a]], b));

var array = [1, 2, 3];

swap(array, 0, 1)
console.log(array);

【讨论】:

  • @vsemozhetbyt 它有效,它改变了数组,你不应该使用函数的返回值。
  • 为了使用流畅的界面,你可以在交换后返回数组。
  • 哦,对不起。我习惯于不使用带有隐式返回的收缩语法的副作用箭头函数)
【解决方案2】:

在 es6 中,交换数组元素的惯用方式是:

;[a[i], a[j]] = [a[j], a[i]]

使用.reduce 不适合此任务。从技术上讲,您可以这样做:

a = a.reduce((acc, element, idx) => {
    acc.push(idx === i ? a[j] : idx === j ? a[i] : a[idx])
    return acc
}, [])

但它会导致复杂的代码。

如果您的目标是避免改变原始数组,您可以使用Object.assign

b = Object.assign([], a, {[i]: a[j], [j]: a[i]})

【讨论】:

    【解决方案3】:

    reduce 函数将数组缩减为对象的值,由 accumulator 定义。

    let array1 = [2, 5, 8, 0, 10];
    let array2 = [1, 4, 9, 7, 6];
    
    const reducer = (accumulator, currentValue) => accumulator + currentValue;
    
    // 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer));
    // expected output: 10
    
    // 5 + 1 + 2 + 3 + 4
    console.log(array1.reduce(reducer, 5));
    // expected output: 15

    sort() 方法对数组的元素进行就地排序并返回该数组。默认排序顺序是基于将元素转换为字符串,然后比较它们的 UTF-16 代码单元值序列。

      
    
    var months = ['March', 'Jan', 'Feb', 'Dec'];
    months.sort();
    console.log(months);
    // expected output: Array ["Dec", "Feb", "Jan", "March"]
    
    const sortingAccending = (a, b) => a - b
    
    let numbers = [4, 2, 5, 1, 3];
    numbers.sort(sortingAccending);
    console.log(numbers);
    // expected output: Array [1, 100000, 21, 30, 4]

    你回答你的问题,reduce 不能用于交换元素。 您将不得不使用sort 编写您的自定义排序function

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 2020-11-06
      • 1970-01-01
      • 2010-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多