我有 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)
并使用该值来填充插槽,但我不确定最简洁的语法是什么样的。
诀窍是弄清楚物品的去向。如果元素的数量不均匀地适合输出数组,每个索引将为每个前一个项目向右推送一个以平均分配开销:
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; }
您可以使用
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));