gpt4 book ai didi

javascript - 加入前两个元素并创建新数组?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:53:53 24 4
gpt4 key购买 nike

在使用 join()slice() 函数数小时后,我发现您不能在复杂数组上使用任何一个函数。所以我来这里寻求帮助。

我正在尝试获取以下数据:

 var data = [
["North", "Tennis",37, 25, 11, 9, 42, 13],
["East", "Football", 41, 2, 3, 26, 47, 21],
["South", "Rugby", 7, 22, 35, 45, 11, 46],
["West", "Rugby", 30, 21, 44, 23, 4, 47],
["North East", "Football", 35, 27, 12, 39, 34, 13],
["North West", "Football", 23, 4, 41, 35, 9, 47]
];

看起来像这样(输出):

var result = [
["North: Tennis", 37, 25, 11, 9, 42, 13],
["East: Football", 41, 2, 3, 26, 47, 21],
["South: Rugby", 7, 22, 35, 45, 11, 46],
["West: Rugby", 30, 21, 44, 23, 4, 47],
["North East: Football", 35, 27, 12, 39, 34, 13],
["North West: Football", 23, 4, 41, 35, 9, 47]
];

任何帮助将不胜感激

最佳答案

当您想要将一个数组转换为另一个数组时,通过获取每个子数组的前两个元素并将它们连接在一起,然后构建一个 .map 原始数组到另一个数组是有意义的通过将其余元素(我们在数组解构期间使用 rest 参数获得)添加到包含连接字符串的新数组来创建新的子数组。

let data = [
["North", "Tennis",37, 25, 11, 9, 42, 13],
["East", "Football", 41, 2, 3, 26, 47, 21],
["South", "Rugby", 7, 22, 35, 45, 11, 46],
["West", "Rugby", 30, 21, 44, 23, 4, 47],
["North East", "Football", 35, 27, 12, 39, 34, 13],
["North West", "Football", 23, 4, 41, 35, 9, 47]
];

let result = data.map(([s1, s2, ...rest]) => [`${s1}: ${s2}`, ...rest]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

引用资料:

关于javascript - 加入前两个元素并创建新数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51907855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com