1

Currently I have a unidimensional array, e.g. ['thing1', 'cond1', 'thing2', 'cond2', 'thing3']

I would like to pair each item to create a new multidimensional array like so [['thing1', 'cond1'], ['thing2', 'cond2'], ['thing3']]. I don't mind the last item being ['thing3', undefined] – if anything this is preferable unless someone raises this as bad practice.

So far I have

const pair = (arr) => {
  let paired = [];

  for (i = 0; i < arr.length; i += 2) {
    paired.push([arr[i], arr[i+1]]);
  }

  return paired;
}

You can try this out in my JS Bin example.

This works perfectly fine AFAIA but I'd love this to be as concise as possible using modern JS and I'm not as polished as I should be with my array manipulation.

Thanks in advance to everyone who gives this a go.

Let the challenge... BEGIN!

Lily
  • 41
  • 5

2 Answers2

2

You could take a while loop with an index variable. For pushing a pair take slice.

const pair = array => {
    let paired = [],
        i = 0;

    while (i < array.length) paired.push(array.slice(i, i += 2));

    return paired;
}

var array = ['thing1', 'cond1', 'thing2', 'cond2', 'thing3'],
    paired = pair(array);

console.log(paired);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can try this regex. Group the values by finding the number by using regular expression.

const data = ['thing1', 'cond1', 'thing2', 'cond2', 'thing3'];
const result = {};

data.forEach(value => {
 const index = value.replace(/[^\d.]/g, '');
    if (typeof result[index] == 'undefined') {
     result[index] = [];
    }
    result[index].push(value);
});

const array = Object.values(result);
console.log(array);
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30