Home > Enterprise >  How to join an n-dimension array with different separators for each level?
How to join an n-dimension array with different separators for each level?

Time:01-07

Sample input

Array

Here I am showing a 3-dimension array but the actual number of dimensions vary and is known as n.

[
  [
    [1,2],
    [3,4]
  ],
  [
    [5,6],
    [7,8]
  ]
]

Separators

It has the same length (n) as the number of dimensions of the array where the i-th element represent the separator of the i-th level of the array.

[',', '_', '-']

Desired output

1-2_3-4,5-6_7-8

What I've tried

It works for a 3-dimension array but not for a 4-dimension one.

I know what is going wrong with my code but I have no idea how to fix it.

Besides, I think there are simpler and/or more efficient methods.

3-dimension (working)

const array = [[[1,2],[3,4]],[[5,6],[7,8]]];
const separators = [',', '_', '-'];
const _separators = separators.reverse();
let i;
function join(array, first = false) {
  const next = Array.isArray(array[0]);
  let result;
  if (next) {
     result = array.map(e => {
       if (first) { i = 0; }
       return join(e);
     });
     i  ;
     result = result.join(_separators[i]);
  }
  else {
    result = array.join(_separators[i]);
  }
  return result;
}
const result = join(array, true);
console.log(result);

4-dimension (not working properly)

const array = [[[[1,2],[3,4]],[[5,6],[7,8]]],[[['A','B'],['C','D']],[['E','F'],['G','H']]]];
const separators = ['|', ',', '_', '-'];
const _separators = separators.reverse();
let i;
function join(array, first = false) {
  const next = Array.isArray(array[0]);
  let result;
  if (next) {
     result = array.map(e => {
       if (first) { i = 0; }
       return join(e);
     });
     i  ;
     result = result.join(_separators[i]);
  }
  else {
    result = array.join(_separators[i]);
  }
  return result;
}
const result = join(array, true);
console.log(result);
// desired output: 1-2_3-4,5-6_7-8|A-B_C-D,E-F_G-H

CodePudding user response:

Something like this with recursion

const join = (array, separators, depth) => {
  if (depth < separators.length -1) {
    return array.map(el => join(el, separators, depth   1)).join(separators[depth]);
  } else {
    return array.join(separators[depth]);
  }
};

{
  const array = [[[1,2],[3,4]],[[5,6],[7,8]]];
  const separators = [',', '_', '-'];
  console.log(join(array, separators, 0));
}
{
  const array = [[[[1,2],[3,4]],[[5,6],[7,8]]],[[['A','B'],['C','D']],[['E','F'],['G','H']]]];
  const separators = ['|', ',', '_', '-'];
  console.log(join(array, separators, 0));
}

  •  Tags:  
  • Related