转换JavaScript数组

Transform JavaScript array

本文关键字:数组 JavaScript 转换      更新时间:2023-09-26

我正在从服务器上获取数据数组,但来到jquery数据表后,我需要多点数组。有什么方法可以让它在jquery本身beflore中传递给数据表吗?

我的输入格式是:

["computer","program","laptop","monitor","mouse","keybord","cpu","harddrive"......]

预期格式:

[["computer","program","laptop","monitor"],["mouse","keybord","cpu","harddrive"],[....],[....]........]

有没有解析数据格式的方法?

转换数组只需要一个简单的while循环。

// This is the original data we get from the server
var input  = ["computer","program","laptop","monitor","mouse","keybord","cpu","harddrive"];
// Make a copy of the input, so we don't destroy it
var data = input.slice(0);
// This is our output array
var output = [], group;
// A while loop will transform the plain array into a multidimensional array
while (data.length > 0) {
    // Take the first four items
    group = data.splice(0, 4);
    // Make sure the group contains 4 items, otherwise pad with empty string
    while (group.length < 4) {
        group.push("");
    } 
    // Push group into the output array
    output.push(group);
}
// output = [["computer","program","laptop","monitor"],["mouse","keybord","cpu","harddrive"]]

更新:甜菜根甜菜根的评论不再有效,因为我们创建了输入的副本

不久前,当我遇到类似的问题时,我发现了这个漂亮的问题。这是一个基于以下内容的解决方案:

var a = ["computer", "program", "laptop", "monitor", "mouse", "keybord", "cpu", "harddrive", "tablet"],
    n = a.length / 4,
    len = a.length,
    out = [],
    i = 0;
while (i < len) {
    var size = Math.ceil((len - i) / n--);
    out.push(a.slice(i, i + size));
    i += size;
}
alert(JSON.stringify(out));

来自未来的消息;)-现在我们有减少:

function groupArray(array, groupSize) {
  return array.reduce((a, b, i) => {
    if (!i || !(i % groupSize)) a.push([])
    a.slice(-1).pop().push(b)
    return a
  }, [])
}
console.log(groupArray(input, 4))
//   [ 
//     [ 'computer', 'program', 'laptop', 'monitor' ],
//     [ 'mouse', 'keybord', 'cpu', 'harddrive' ] 
//   ]