如何在Javascript中将数组的内容均匀展开并用某个值填充空槽?

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

我有 3 个输入:一个数组、一个总计数整数和一个任意值。

input_array = ['hello', 'there', 'world']
total_count = 15
fill_value = null

期望的输出:

output = [
  'hello',
   null,
   null,
   null,
   null,
   'there',
   null,
   null,
   null,
   null,
   'world',
   null,
   null,
   null,
   null,
]

假设

input_array
的长度不超过
total_count
。其他场景:

  • 如果
    total_count
    3
    ,你会得到
    ['hello', 'there', 'world']
  • 如果
    total_count
    4
    ,你会得到
    ['hello', null, 'there', 'world']
  • 等等等

这感觉像是递归函数的候选?您可以使用

Math.ceil((total_count - input_array.length) / input_array.length)
并使用该值来填充插槽,但我不确定最简洁的语法是什么样的。

javascript arrays recursion fill spread
2个回答
1
投票

诀窍是弄清楚物品的去向。如果元素的数量不均匀地适合输出数组,每个索引将为每个前一个项目向右推送一个以平均分配开销:

function fillPadded(arr, count, fillWith){
  const filled = Array(count).fill(fillWith)
  const step = Math.floor(count/arr.length)
  const offs = count%arr.length
  for(let i = 0; i < arr.length; i++){
    const pos = i*step + (i <= offs ? i : offs)
    filled[pos] = arr[i]
  }
  return filled
}

console.log(JSON.stringify(fillPadded(['hello', 'there', 'world', 'foo'], 9, null)))
console.log(JSON.stringify(fillPadded(['hello', 'there', 'world', 'foo'], 10, null)))
console.log(JSON.stringify(fillPadded(['hello', 'there', 'world', 'foo'], 11, null)))
console.log(JSON.stringify(fillPadded(['hello', 'there', 'world'], 15, null)))
.as-console-wrapper { max-height: 100% !important; top: 0; }


0
投票

您可以使用

Array#flatMap
构造最终数组。

function createArr(initial, count, fill) {
  const each = Math.floor(count / initial.length) - 1, rem = count % initial.length;
  return initial.flatMap((x, i) => [x, ...Array(each + (i < rem)).fill(fill)]);
}
console.log(createArr(['hello', 'there', 'world'], 15, null));
console.log(createArr(['hello', 'there', 'world'], 4, null));
console.log(createArr(['hello', 'there', 'world'], 3, null));

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