Kyle
Kyle

Reputation: 1183

Recursive function to flatten multidimension array

I am trying to flatten a multidimensional array into a one dimensional array using a recursive function.

My single dimension array elements is returning undefined

JS Bin with my example, here.

HTML:

<span class="one"></span>
<span class="one"></span>

<span class="two"></span>

JS:

// elements collection
var elementsCollection = [];
var elements = [];

/*  toSingle
*  convert mutlidimensional array to one dimensional array (i.e. flatten)
*
*  @param ec - array
*/
function toSingle (ec) {
    for (var i = 0; i < ec.length; i++) {
        if (ec[i].length) {
            toSingle(ec[i])
        }
        else {
            elements.push(ec[i]);
        }
    }
}

// get elements by their HTML class name
var buttons = [ 'one', 'two' ];

// collect elements from class names
for (var i = 0; i < buttons.length; i++) {
  elementsCollection.push(document.getElementsByClassName(buttons[i]));
}

// convert multiDimensional array to one dimensional
elements = toSingle(elementsCollection);

// log
console.log(elements);  // undefined 

Upvotes: 1

Views: 180

Answers (2)

scraaappy
scraaappy

Reputation: 2886

First point, you can use querySelectorAll() to avoid an useless loop (and pass an array as argument, as it will be coerced toString).

Second, if you don't mind using es6's features, just spread the received object in an array. Only two lines left:

(also be aware that, although this doesn't seem to be the case in your example, with @Ele's solution, you have to remove duplicates in case you have elements having both or more classes)

var buttons = ['.one', '.two','.three'];
var elements =[...document.querySelectorAll(buttons)];

console.log(elements);
<span class="one two"></span>
<span class="one two three"></span>
<span class="two one four"></span>
<span class="one"></span>
<span class="two three"></span>

Upvotes: 0

Ele
Ele

Reputation: 33726

You need to return the array elements.

A recommendation is putting that array elements into the function toSingle

/*  toSingle
 *  convert mutlidimensional array to one dimensional array (i.e. flatten)
 *
 *  @param ec - array
 */
function toSingle(ec) {
  var elements = [];
  for (var i = 0; i < ec.length; i++) {
    if (ec[i].length) {
      elements = elements.concat(toSingle(ec[i]));
    } else {
      elements.push(ec[i]);
    }
  }

  return elements
}

// get integers, first, previous, next, last buttons by their HTML class name
var buttons = ['one', 'two'];

// elements collection
var elementsCollection = [];
// collect elements from class names
for (var i = 0; i < buttons.length; i++) {
  elementsCollection.push(document.getElementsByClassName(buttons[i]));
}

// convert multiDimensional array to one dimensional
var elements = toSingle(elementsCollection);

// log
console.log(elements);
<span class="one"></span>
<span class="one"></span>
<span class="two"></span>

Upvotes: 1

Related Questions