Instantly share code, notes, and snippets.

Embed
What would you like to do?
Array transformation for javaScript
/**
* Arrays to parse.
*/
const array_one = ["one", "two", "three", "four"];
const array_two = ["three", "four", "five", "six"];
const big_one = ["one", "two", "three", "four","three", "four", "five", "six"];
const array_number = [1, 10, 100, 9, 7, 5, 4, 55, 76, 45, 32, 92, 41];
const array_obj_number = [{'val': 1}, {'val': 10}, {'val': 100}, {'val': 9}, {'val': 7}, {'val': 5}, {'val': 4}, {'val': 55}, {'val': 76}];
/**
* UNION : Get the union of the two arrays
*/
let union = array_one.filter((x) => array_two.indexOf(x) >= 0);
// union => Array [ "three", "four" ]
/**
* DISTINCT : Get the element not common in array_one and array_two __NOTA__ : need the union variable
*/
let distinct = array_one.concat(array_two).filter((x) => union.indexOf(x) === -1);
let distinctV2 = array_one.concat(array_two).filter((x) => array_one.filter((x) => array_two.indexOf(x) >= 0).indexOf(x) === -1);
// distinct => Array [ "one", "two", "five", "six" ]
// distinctV2 => Array [ "one", "two", "five", "six" ]
/**
* UNIQ: filter array getting only uniq value
*/
let uniq = big_one.filter(function(elem, pos,arr) {return arr.indexOf(elem) === pos;});
// uniq => Array [ "one", "two", "three", "four", "five", "six" ]
/**
* Int stuff max/min/sum/avg
*/
let max = Math.max.apply(Math, array_number); // max = 100
let min = Math.min.apply(Math, array_number); // min = 1
let sum = array_number.reduce(function (u, a) { return u + a; } , 0); // sum = 477
let avg = sum / array_number.length; // need sum => avg = 36.69...
let stddev = Math.sqrt(array_number.map(function(v){ let d = v - avg; let s = d * d; return s; }).reduce(function (u, a) { return u + a; } , 0)/array_number.length);
// standard deviation => stddev = 33,7.. need avg
/**
* Array of object stuff max/min/sum/avg
*/
let max_obj = Math.max.apply(Math, array_obj_number.map(function (o) { return o.val })); // max_obj = 100
let min_obj = Math.min.apply(Math, array_obj_number.map(function (o) { return o.val })); // min_obj = 1
let sum_obj = array_obj_number.map(function (o) { return o.val }).reduce(function (u, a) { return u + a; } , 0); // sum = 267
let avg_obj = sum_obj / array_obj_number.length;
let stddev_obj = Math.sqrt(array_obj_number.map(function (o) { return o.val }).map(function(v){ let d = v - avg_obj; let s = d * d; return s; }).reduce(function (u, a) { return u + a; } , 0)/array_obj_number.length);
// standard deviation => stddev_obj = 35.20.. need avg_obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment