循环以将数组中的元素移位到末尾

问题描述 投票:0回答:3

假设我有一个数组

let arr = [
    [0,1,0,4],
    [1,0,1,2],
    [0,0,1,1],
    [0,1,0,1]
];

我想循环使用更高阶数组函数的数组,并返回一个数组,其中所有不等于n的值(在我的情况下,假设n=0)将堆叠在数组的末尾:

console.log( arr.map( certainFunction ) );
//returns this;
[ [0,0,1,4],
  [0,1,1,2],
  [0,0,1,1],
  [0,0,1,1] ]

是否可以使用更高阶函数循环通过arr并返回上面的数组?那么certainFunction怎么样?

javascript arrays sorting higher-order-functions
3个回答
3
投票

高阶函数,如有序;)

let separate = n => a => a.filter(x => x === n).concat(a.filter(x => x !== n));

//

let arr = [
    [0,1,0,4],
    [1,0,1,2],
    [0,0,1,1],
    [0,1,0,1]
];


newArr = arr.map(separate(1)) // move 1's to the start

console.log(newArr.map(x => x.join()))

或者,使用更多功能编程:

let eq = a => b => a === b;
let not = f => a => !f(a);

let separate = n => a => a.filter(eq(n)).concat(a.filter(not(eq(n))));

1
投票

这可以通过保持一个球门柱并将所有arr[i] != n推回到该指数来线性地完成。

function push_to_end (arr, n=0) {
  // Begin by pushing items to the very end.
  let index = arr.length - 1
  for (let i = index; i > -1; i--) {
    // If you encounter an integer not equal to end, place it
    // at `index` and move the goalpost back one spot.
    if (arr[i] !== n)
      arr[index--] = arr[i]
  }

  // Fill everything up to the goalpost with `n`, as that is how
  // many times we observed n.
  for (let i = 0; i <= index; i++) {
    arr[i] = n
  }

  return arr
}

在您的情况下,您将此函数应用于数组数组中的每个数组:

arr.map(a => push_to_end(a, n))

0
投票

Array.prototype.sort()

let arr = [
    [0,1,0,4],
    [1,0,1,2],
    [0,0,1,1],
    [0,1,0,1]
];

arr = arr.map(ar => ar.sort((a, b) => a-b));
console.log(arr)

适用于您的情况,不确定您是否希望数字小于n

© www.soinside.com 2019 - 2024. All rights reserved.