Array helper methods
by Konstantin Rouda
HTML
<p class="console"></p>
CSS
HTML {
font-family: sans-serif;
font-size: 100%;
line-height: 1.5;
box-sizing: border-box;
}
BODY {
color: #3a3d40;
margin: 0;
}
*, *::before, *::after {
box-sizing: inherit;
color: inherit;
}
.console {
max-width: 50vw;
margin: 3em auto;
padding: 3em .5em;
font-size: 2em;
border: 2px solid rgba(70, 70, 70, .9);
border-radius: .1em;
text-align: center;
}
JavaScript
;(function() {
"use strict";
/*=======================
Unique
=========================*/
/*
Returns the array after removing duplicate values from it
*/
if(!Array.prototype.unique) { // method on the Array.prototype
Array.prototype.unique = function() {
return Array.prototype.filter.call(this, function(v, i, arr) {
return Array.prototype.indexOf.call(this, v) === i;
}, this);
};
/*
/// using Arrow function's lexical `this`,
/// i.e. the arrow functions capture the `this` value of the enclosing context/function.
Array.prototype.unique = function() {
return Array.prototype.filter.call(this, (v, i) => {
return Array.prototype.indexOf.call(this, v) === i;
});
};*/
};
/*== standalone function ==*/
/**
* Gets array, filters it to preserve only unique values (e.g. arr = [1, 2, 3, 3, 2, 1, 4] => [1, 2, 3, 4])
* @param {Array} arr - Array or Array Like Object to filter it values
* @return {Array} - Filtered array with only unique values.
*/
function getUniqueValues (arr) {
return Array.prototype.filter.call(arr, function(v, i, arr) {
return Array.prototype.indexOf.call(arr, v) === i;
});
};
//// TEST
/*
var arr = [1, 2, 1, 3, 2, 4, 5, 4, 6, 5, 7, 8, 9, 10, 6, 5, 1];
var uniqueArr = arr.unique();
display(uniqueArr);
console.log("unique array: ", uniqueArr);
*/
/*=======================
Partition
=========================*/
/*
Returns 2 arrays one whose elements satisfy the predicate and
the second whose elements don't saisfy the predicate
*/
if(!Array.prototype.partition) {
Array.prototype.partition = function(predicate) {
var resultArr = [], truthyArr = [], falsyArr = [];
Array.prototype.forEach.call(this, function(v) {
if(predicate(v)) {
truthyArr.push(v);
} else {
falsyArr.push(v);
...