将数组的多个项目映射到单个对象/函数

Mapping multiple items of an array to a single object / function

本文关键字:单个 对象 函数 映射 项目 数组      更新时间:2023-09-26

考虑以下数组:

['123', '456', '789', '000', '111', '222', '333', '444', '555']

现在,假设我想将每 3 个项目映射到一个函数。

也就是说,123456789都会映射到function () { ... }

接下来000111222将被映射到另一个function () { ... }

我想这样做是因为我需要对数据库执行批处理请求,但我可以请求的最大 ID 数量是每批 25 个。

所以我的目标是将每 25 个项目映射到一个函数(将执行批处理请求),然后使用 async.parallel 并行执行每个函数。

问题是我不能使用 mapasync.map,因为这会映射数组上的每个项目。我打算做的是将每个 25 个连续项目映射到单个对象/函数。

这可能吗?

我正在寻找任何JavaScript或NodeJS解决方案。

与 Node 不完全相关.js但这里有一个可能的解决方案:

var funcs = [a, b, c, ...], // the list of functions
    arr = [], // your data
    items = 25,
    mapOfFuncs = [];
for(var i = 0, len = arr.length, f; i < len; i++){
    f = funcs[Math.floor(i / items)];
    mapOfFuncs.push(f);
}

根据观察,每 24 个连续数字除以 25 并下限将产生相当于相应函数索引的某个数字。

它将产生一个数组mapOfFuncs,该数组将具有对应于arr元素的函数。例如,对于arr = ['123', '456', '789', '000', '111', '222', '333', '444', '555']items = 3,输出将是:[a, a, a, b, b, b, c, c, c]

更像这样吗?

function groupBy(size, arr){
    for(var i=0, out=[]; i<data.length; i+=size)
        out.push( data.slice(i, i+size) )
    return out;
}
var data = ['123', '456', '789', '000', '111', '222', '333', '444', '555']; 
async.parallel(groupBy(3, data).map( part => processData.bind(null, part) ), callback);
//or
async.parallel(groupBy(3, data).map( part => ()=>processData(part) ), callback);
//or
async.map(groupBy(3, data), processData, callback);

> javascript 函数splice可以在这里使用,以将每 3(或 25)个元素从原始数组中分离出来。

旁注:请注意,拼接会修改原始数组。

// this removes the first n elements out of the array and returns them
var batch= data.splice(0, length)

这是一个完整的解决方案:

var data = ['123', '456', '789', '000', '111', '222', '333', '444', '555']
    , length = 3
// this function is called recursively until the whole initial array is processed (and emptied)
function splitTable() {
  var batch= data.splice(0, length)
    // process your batch here (map to the function you want)
    console.log('batch' + batch)

  if (data.length)
    splitTable()
}
// initial call of the function
splitTable()

演示