转换JavaScript数组
Transform JavaScript array
我正在从服务器上获取数据数组,但来到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' ]
// ]
相关文章:
- 如何遍历包含对象的数组-javascript
- 保存数组javascript
- 查找数组javascript中包含的元素类型
- 算法:从数组(javascript/angular)中按当前日期获取上一个和下一个事件
- 从多维数组javascript中提取特定值
- 如何在数组javascript中选择伪随机值
- 拆分字符串数组(JavaScript)后未定义
- 从数组JavaScript中删除并返回最后n个项的最快方法
- 使用条件for循环更新数组-Javascript
- 从数组javascript创建新对象
- 用数组(javascript)中的值替换regex捕获
- 从数组[Javascript]的总长度中减去一个干净的数字
- 将一个字符串数组解析为一个新的数组javascript
- 如何将对象转换为对象数组javascript
- 赢得't循环数组javascript
- 从不同的数组 JavaScript 中获取值
- 多维数组 JAVASCRIPT 出了点问题
- 可以't分配给一个对象数组javascript
- 比较数组JavaScript中的对象
- 如何完成缺少(连续)元素的数组|Javascript