lodashSandbox:first
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>
_.head (aka _.first)
</h3>
</div>
<div class="subtitle">
<h4>
return first element of array or undefined if array empty
</h4>
</div>
<div class="workspace">
<textarea id='startInput' type='textarea' rows=5>[
1, { "user": "barney", "active": true },
{ "user": "fred", "active": false },
{ "user": "pebbles", "active": false }
]</textarea>
<label for="startInput">array to search</label>
<br />
<div class="actionArea">
<button id="button1">first</button>
<br /><br />
<button id="button2">first when empty</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");
_.head([1, 2, 3]);
// => 1
_.head([]);
// => undefined
button1.onclick = () => {
doOperation1();
}
button2.onclick = () => {
doOperation2();
}
function doOperation1() {
let inputVal = JSON.parse(startInput.value);
output.value = (JSON.stringify(_.first(inputVal)));
}
function doOperation2() {
let inputVal = [];
output.value = (_.first(inputVal));
}
function doOperation3() {
let inputVal = JSON.parse(startInput.value);
output.value = (_.findLastIndex(inputVal, function(o) { return o.user === searchProperty;}));
}