以功能方式交换两个数组元素

时间:2017-02-15 19:57:15

标签: javascript functional-programming

我试图在javascript中以函数方式交换数组中的2个元素(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]

我能想到的唯一方法是:

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

但是这个代码在数组上运行两次,根本不可读。 有关一个漂亮干净的功能代码的任何建议吗?

感谢。

6 个答案:

答案 0 :(得分:6)

简短而可靠,但难以理解:

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

答案 1 :(得分:3)

好的ol'



const a = [1,2,3,4,5]

const swap = (start, end, arr) =>
  [].concat(
    arr.slice(0, start), 
    arr.slice(end,end+1), 
    arr.slice(start+1,end), 
    arr.slice(start,start+1)
  )
  
console.log(swap(2, 4, a))




纯功能性,可读性,虽然有点长

答案 2 :(得分:2)

一张地图'也会这样做:

function swap(arr, a, b) {
  return arr.map((it, idx) =>
    (idx === a) ? arr[b] :
    (idx === b) ? arr[a] : it
  );
}

答案 3 :(得分:1)

您可以使用解构赋值来交换数组的索引。如果预期结果是新数组,则在传递给Array.prototype.slice()的数组上调用swap(),否则省略let copy = _arr.slice(0)和引用_arr arr解构分配。

let arr = [1,2,3,4,5,6];
let swap = (_arr, a, b) => {
  let copy = _arr.slice(0);
  [copy[a], copy[b]] = [copy[b], copy[a]];
  return copy
};
let result = swap(arr, 1, 2); 
console.log(result, arr);

答案 4 :(得分:0)

多么有趣的小问题 - 应该注意确保abxs上的有效索引,但我会留给您。< / p>

&#13;
&#13;
const swap = (a,b) => (arr) => {
  const aux = (i, [x, ...xs]) => {
    if (x === undefined)
      return []
    else if (i === a)
      return [arr[b], ...aux(i + 1, xs)]
    else if (i === b)
      return [arr[a], ...aux(i + 1, xs)]
    else
      return [x, ...aux(i + 1, xs)]
  }
  return aux (0, arr)
}


let xs = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

// same index doesn't matter
console.log(swap(0,0) (xs)) // [a, b, c, d, e, f, g]

// order doesn't matter
console.log(swap(0,1) (xs)) // [b, a, c, d, e, f, g]
console.log(swap(1,0) (xs)) // [b, a, c, d, e, f, g]

// more tests
console.log(swap(1,3) (xs)) // [a, c, d, b, e, f, g]
console.log(swap(0,6) (xs)) // [g, b, c, d, e, f, a]
console.log(swap(5,6) (xs)) // [a, b, c, d, e, g, f]

// don't fuck it up
console.log(swap(7,3) (xs)) // [a, b, c, undefined, e, f, g]

// empty list doesn't matter
console.log(swap(3,2) ([])) // []
&#13;
&#13;
&#13;

答案 5 :(得分:-1)

返回新数组(函数编程):

SELECT (~QUERY~) RESULT ,SYSDATE DATETIME FROM DUAL;

操纵输入数组(非函数编程):

const swap = (arr, a, b)=> { let copy = arr.slice(0); copy[b] = [copy[a], copy[a] = copy[b]][0]; return copy; }