以功能性方式交换两个数组元素 [英] Swap two array elements in a functional way

查看:51
本文介绍了以功能性方式交换两个数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript(es6)中的功能方式交换数组中的2个元素

I'm trying to swap 2 elements within an array in a functional way in javascript (es6)

let arr = [1,2,3,4,5,6]
let result = swap(arr, 1, 2) // input: array, first element, second element
// result=[1,3,2,4,5,6]

我唯一能想到的方法是:

The only way I could think about is:

const swap = (arr, a, b) => 
            arr.map( (curr,i) => i === a ? arr[b] : curr )
               .map( (curr,i) => i === b ? arr[a] : curr )

但是此代码在数组上运行了两次,并且根本不可读.有什么好的简洁功能代码的建议吗?

But this code runs twice over the array, and not readable at all. Any suggestions for a nice clean functional code?

谢谢.

推荐答案

简短可靠,但难以理解:

Short and reliable but admittedly hard to read:

const swap = (x, y) => ([...xs]) => xs.length > 1
 ? ([xs[x], xs[y]] = [xs[y], xs[x]], xs)
 : xs;

const xs = [1,2,3,4,5];

const swap12 = swap(1, 2);

console.log(
  swap12(xs),
  "exception (one element):",
  swap12([1]),
  "exception (empty list):",
  swap12([])
);

这篇关于以功能性方式交换两个数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆