How to click an element on index 0 of an array

I have a situation

i has 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 is : how do I push item from array1 to make my array2 look like

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

so that I can define index:0 as category .

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

if I can get the key value array pair, which would be good for me.

my data:

 array1 = ["fruit","vegetables"]; array2 = [["apple","banana"],["tomato"]]; //expected output :[["fruit","apple","banana"],["vegetables","tomato"]]; 
+5
source share
2 answers

Use 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) 

UPDATE: If you do not want to create a new array, you can avoid copying.

 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 Function ES6 arrow :

 var array1 = ["fruit", "vegetables"], array2 = [ ["apple", "banana"], ["tomato"] ]; array2.forEach((v, i) => v.unshift(array1[i])); console.log(array2) 
+3
source

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

 array1 = ["fruit","vegetables"]; array2 = [["apple","banana"],["tomato"]]; array2.map((a,i) => a.unshift(array1[i])) console.log(array2) 
+3
source

Source: https://habr.com/ru/post/1262413/


All Articles