D
D
dom1n1k2017-01-24 19:30:27
JavaScript
dom1n1k, 2017-01-24 19:30:27

Algorithm for turning a single-level list into a two-level one?

There is an array containing elements of two types (although in the general case there may be more than two types, but for now you can score on this). Specific objects are unimportant, let them be numbers and letters for clarity. It is necessary to combine consecutive elements of the same type into subarrays. For example:

[1, 2, a, b] => 
[1, 2, 3, a, 4, 5, b, 9, n, m] => 
[1] => 
[a] => 
[] => []

It seems to be not at all a difficult task, but the solutions turn out to be something very clumsy. Surely there is some beautiful and elegant, but apparently I'm stupid.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2017-01-24
@dom1n1k

var arr = [1, 2, 3, 'a', 4, 5, 'b', 9, 'n', 'm'];
arr = arr.reduceRight(function(prev, el, i) {
  if (prev.length == 0 || 
     (typeof(el) != typeof(prev[0][0]))) {
    prev.unshift([el]);
  } else {
    prev[0].unshift(el);
  }
  return prev;
}, []);
console.log(JSON.stringify(arr));

D
dom1n1k, 2017-01-24
@dom1n1k

Here is what I myself gave birth to and what can be called more or less decent:

function group (input) {

  var last = function (arr) {
    return arr[arr.length - 1];
  }

  var output = [];
  input.forEach(function (el) {
    if (output.length === 0 || typeof(el) !== typeof(last(output)[0])) {
      output.push([]);
    }
    last(output).push(el);
  });

  return output;
}

D
Dark Hole, 2017-01-24
@abyrkov

ES6 could be more elegant?

let arr = [...], result = , cur = 0;
for(let val of arr)
  if(arr[cur].length == 0 || typeof arr[cur][0] == typeof val) arr[cur].shift(val);
  else cur++, arr[cur] = [val];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question