Home > Software design >  How can I multiply an array length to manipulate another array in js
How can I multiply an array length to manipulate another array in js

Time:12-02

Here are my arrays:

arr1=['a','b','c']
arr2=[[0,0],[0,0,0,0],[0,0,0]]

What I want is getting this result:

arr1['a','a','b','b','b','b','c','c','c']

I mean یepending on the length of the second array, the elements of the first array must be repeated. Both arr1 and arr2 are always equal in terms of elements.(3 here)

CodePudding user response:

const arr3 = arr1
  .map((item, index) => Array(arr2[index].length).fill(item))
  .flat();

CodePudding user response:

1) You can use flatMap here as:

const arr1 = ["a", "b", "c"];
const arr2 = [
  [0, 0],
  [0, 0, 0, 0],
  [0, 0, 0],
];

const result = arr1.flatMap((c, i) => Array(arr2[i].length).fill(c));

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

2) You can also use flatMap and Array.from here as:

const arr1 = ["a", "b", "c"];
const arr2 = [
  [0, 0],
  [0, 0, 0, 0],
  [0, 0, 0],
];

const result = arr2.flatMap((na, i) => Array.from({ length: na.length }, () => arr1[i]));

console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can use two forEach loops like this :

arr1 = ['a', 'b', 'c']
arr2 = [[0, 0], [0, 0, 0, 0], [0, 0, 0]]

let result = [];

arr2.forEach((element, index) => {
    element.forEach(() => {
       result.push(arr1[index]);
    });
});

console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

const arr1 = ['a','b','c'];
const arr2 = [[0,0],[0,0,0,0],[0,0,0]];

const res = arr2.map((v,i) => v.map(a => arr1[i])).flat();

console.log( res );
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related