Matias
Matias

Reputation: 332

Create two dimensional array from two arrays

I've got these two arrays and I need to obtain c. I managed to obtain a solution with two fors and conditionals, but I'm sure something better than O^2 can be obtained with JS.

a = [3, 2, 1, 3]
b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

c = [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]

Upvotes: 2

Views: 160

Answers (4)

phhu
phhu

Reputation: 1992

One possibility is to combine map with splice, taking care not to mutate the original array:

const a = [3, 2, 1, 3];
const b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];

function slices(sizes, arr){
  const clonedArr = [].concat(arr);     // clone array to prevent mutation 
  return sizes.map(size => clonedArr.splice(0,size));
}

console.log(slices(a,b));     // [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]

Alternatively, avoiding mutation altogether, you could use slice with a slightly convoluted reduce:

const slicesByReduce = (sizes, arr) => sizes
  .reduce(({start, acc}, size) => ({
    start: start + size,
    acc: [...acc, arr.slice(start, start + size)]
  }),{
    start: 0,
    acc: []
  }).acc;

console.log(slicesByReduce(a,b));     // [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]

Upvotes: 2

Wiidialga18
Wiidialga18

Reputation: 331

For fun purpose I wrote it in a coincisive way, hope you like it:

const a = [3, 2, 1, 3];
const b = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
const bClone = [...b];

const array = a.map((num, index) =>
  Array.from({ length: num }, () => bClone.shift())
);

console.log(array);

Of course controls should be added, thanks

Upvotes: 4

Ricardo Aranguren
Ricardo Aranguren

Reputation: 650

Iterate your array of "sizes" and get slices of the second array into the result, like this:

const a = [3, 2, 1, 3]
const b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

const c = [];
var index = 0;
for (var size of a) {
    c.push(b.slice(index, index + size));
    index += size;
}
  
console.log(c)
//c = [['a', 'b', 'c'], ['d', 'e'], ['f'], ['g', 'h', 'i']]

Also, if you are going to work with arrays in JavaScript, please look into:

  • initializing variables with var, let and const
  • using push()
  • for loops

Upvotes: 1

Alan Omar
Alan Omar

Reputation: 4227

I don't have that much good background in algorithms but I think this is better than two fors:

let a = [3, 2, 1, 3]
,b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

let head = 0

let result = a.map((e) => {
      let subArr = b.slice(head,head+e)   
      head +=e
      return subArr
  })
  
 console.log(result)

Upvotes: 2

Related Questions