13

i have a situation like this,

i have 2 array1 as array1 = ["fruit","vegetables"];

and

array2 = [["apple","banana"],["tomato"]]; // index 0:represent fruit i,e (["apple","banana"]), index 1: vegetables i,e (["tomato"])

my question : how can i push item from array1 so as to make my array2 look like this

[["fruit","apple","banana"],["vegetables","tomato"]];

with that i can determine index:0 as category.

MY data structure is these 2 array array1 = ["fruit","vegetables"]; AND array2 = [["apple","banana"],["tomato"]];

if i'm able to get key value pair array that would good for me.

my sample data:

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


array2 = [["apple","banana"],["tomato"]]; //expected output :[["fruit","apple","banana"],["vegetables","tomato"]];

2 Answers2

5

Use Array#unshift method.

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)

UPDATE : If you don't want to create a new array then you can avoid the copying part.

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)

With ES6 arrow function :

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

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

console.log(array2)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
2

Try this Array.map() and Array.unshift() .unshift() push the data into array [0]index position.

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

array2.map((a,i) =>  a.unshift(array1[i]))
console.log(array2)
prasanth
  • 22,145
  • 4
  • 29
  • 53