join array of arrays code example

Example 1: javascript array flatten

// flat(depth), 
// depth is optional: how deep a nested array structure 
//		should be flattened.
//		default value of depth is 1 

const arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 2: js convert array of arrays to array

// Converts array with multiple values into a single array with all items:
var merged = [].concat.apply([], arrays);

Example 3: .join in javascript

const elements = ['Sun', 'Earth', 'Moon'];

console.log(elements.join());
// output: "Sun,Earth,Moon"

console.log(elements.join(''));
// output: "SunEarthMoon"

console.log(elements.join('-'));
// output: "Sun-Earth-Moon"

Example 4: flatten an array in javascript

// Although this now may be an older version of how to faltten an 
// array of arrays. I still want to post it so some may have an understanding 
// of how it works

function falltenArray(arr) {
  
  let result = [...arr];
  let flattened = false;
  let counter = 0;
  
  while (flattened === false){
	// checks to see if the element at the counter index is an array
      if (Array.isArray(result[counter])){
        // unpacks the current array element back into the array
        result.splice(counter, 1, ...result[counter]);
        // if so the counter should start at the beginning of the array
        counter = 0;
        
      } else {
        counter += 1;
      }

      if (counter === result.length){
        flattened = true;
      }
  }
  
  return result;
}

Example 5: Javascript flatten array of arrays

var multiDimensionArray = [["a"],["b","c"],["d"]]; //array of arrays
var flatArray = Array.prototype.concat.apply([], multiDimensionArray); //flatten array of arrays
console.log(flatArray); // [ "a","b","c","d"];

Example 6: join array javascript

<html>
  <select multiple class="select-colors">
    <option>blue</option>
    <option>green</option>
  </select>
</html>  

<script>
  var myColorSelect = $(".select-colors").val().join();
  
 console.log(myColorSelect);
</script>