lodashSandbox:flatten

ES6 Enabled

by David McClelland

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<div class="wrapper">
  <div class="title">
    <h3>
      _.flatten, _.flattenDeep, _.flattenDepth
    </h3>
  </div>
  <div class="subtitle">
    <h4>
      Flatten first level nesting, flatten recursively to remove all nesting, or flatten down to a specified amount in an array
    </h4>
  </div>
  <div class="workspace">
    <textarea id='startInput' type='textarea' rows=5>[1, [2, [3, [4]], 5]]</textarea>
    <label for="startInput">nested array</label>

    <textarea id='depth' type='textarea' rows=1>2</textarea>
    <label for="startInput">depth to flatten</label>

    <br />
    <div class="actionArea">

      <button id="button1">flatten</button>
      <br /><br />

      <button id="button2">flattenDeep</button>
      <br /><br />

      <button id="button3">flattenDepth</button>
    </div>
    <br />
    <textarea id="output" rows="2" value="output"></textarea>
  </div>
</div>

CSS

label {
  font-size: 12px;
}

.wrapper {
  display: flex;
  flex-direction: column;
  width: 500px;
}

.title,
.subtitle,
label {
  font-family: Helvetica;
  color: gray;
}

.workspace {
  display: flex;
  flex-direction: column;
}

.actionArea {
  border: 1px solid #EEEEEE;
  padding: 12px;
}

.actionArea button {
  width: 200px;
}

#output {
  font-family: Courier;
  font-size: 14px;
}

input {
  font-family: Courier;
  font-size: 14px;
  width: 400px;
}

#modValInput {
  font-family: Courier;
  font-size: 14px;
}

Babel + JSX

// find elements
let banner = document.getElementById("#playground");
let button = document.getElementById("button");
let startInput = document.getElementById('startInput');
let output = document.getElementById("output");


button1.onclick = () => {
  doOperation1();
}

button2.onclick = () => {
  doOperation2();
}

button3.onclick = () => {
  doOperation3();
}

function doOperation1() {
	let inputVal = JSON.parse(startInput.value);
  output.value = (JSON.stringify(_.flatten(inputVal)));
}

function doOperation2() {
	let inputVal = JSON.parse(startInput.value);
  output.value = (JSON.stringify(_.flattenDeep(inputVal)));
}

function doOperation3() {
  let depth = Number.parseInt(document.getElementById("depth").value);
	let inputVal = JSON.parse(startInput.value);
  output.value = (JSON.stringify(_.flattenDepth(inputVal, depth)));
}