javascript – 如何在数组的索引0处推送元素[复制]

参见英文答案 > How to insert an item into an array at a specific index?                                    12个
我有这样的情况,

我有2个array1作为array1 = [“fruit”,“vegetables”];

array2 = [[“apple”,“banana”],[“tomato”]]; //索引0:代表水果i,e([“苹果”,“香蕉”]),索引1:蔬菜i,e([“番茄”])

我的问题:我如何从array1推送项目,以使我的array2看起来像这样

[[ “水果”, “苹果”, “香蕉”],[ “蔬菜”, “番茄”]];

我可以确定索引:0作为类别.

我的数据结构是这两个数组array1 = [“fruit”,“vegetables”]; AND array2 = [[“apple”,“banana”],[“tomato”]];

如果我能够获得对我有益的键值对阵列.

我的样本数据:

array1 = ["fruit","vegetables"];


array2 = [["apple","banana"],["tomato"]]; //expected output :[["fruit","apple","banana"],["vegetables","tomato"]];
使用 Array#unshift方法.

var array1 = ["fruit", "vegetables"],
  array2 = [
    ["apple", "banana"],
    ["tomato"]
  ];

var array3 = array2.map(function(v, i) { // iterate over the array to generate the new array
  var arr = v.slice(); // copy the array
  arr.unshift(array1[i]) // insert element at beginning 
  return arr; /// return generated array
});

console.log(array3)

更新:如果您不想创建新阵列,则可以避免复制部分.

var array1 = ["fruit", "vegetables"],
  array2 = [
    ["apple", "banana"],
    ["tomato"]
  ];

array2.forEach(function(v, i) { // iterate over the array 
  v.unshift(array1[i]) // insert element at beginning 
});

console.log(array2)

随着ES6 arrow function

var array1 = ["fruit", "vegetables"],
  array2 = [
    ["apple", "banana"],
    ["tomato"]
  ];

array2.forEach((v, i) => v.unshift(array1[i]));

console.log(array2)
相关文章
相关标签/搜索