Underscore functional javascript - javascript

I'm trying to switch in general to functional programming and want to use underscore for JavaScript.
But I'm stuck at first base. I could not create an array at all and resorted to imperative language, and I can't seem to transform them properly either: n.length is correct, but n[0].length is undefined (see fiddle)
var a = new Array(5);
for (i = 0; i < a.length; i++) {
a[i] = new Array(6);
}
var n = _.map(a, function (row, rowIdx) {
_.map(row, function(col, colIdx) {
return rowIdx * colIdx
});
});
console.log(a.length)
console.log(n.length)
console.log(a[0].length);
console.log(n[0].length);

To "functionally" create a 5 x 6 matrix using underscore, you could do something like this:
var matrix = _.range(5).map(function (i) {
return _.range(6).map(function (j) {
return j * i;
});
});
The _.range function (documentation) is a shorthand for creating arrays that are filled with sequential numbers. For example, _.range(5) returns the array [0,1,2,3,4]. Ranges start at zero.
If you didn't want to use _.range, you could do this with raw JavaScript by using array literals:
var matrix = [0,1,2,3,4].map(function (i) {
return [0,1,2,3,4,5].map(function (j) {
return j * i;
});
});

Another way to create a matrix would be to use _.times:
var matrix = _.times(6, function(x){
return _.times(7, function(y){
// do whatever needs to be done to calculate the value at x,y
return x + ',' + y;
});
});

In ES6/2015
var range = num => Array.apply(null, Array(num)).map((i, n) => n);
var matrix2d = (a1, a2) => a1.map(i => a2.map(j => [i, j]));
console.log(matrix2d(range(5), range(6)));

Related

How to sort and list out the array element, after comparing the sums of each numeric value

This code returns only returns the order of the sums of the numeric value, how do I return the array element in a list arranged by largest sum on top?
For instance, the result should be:
"1234-2722-2343-2842"
"1234-2722-2343-2345"
"1234-2322-2343-2342"
Code:
var addSum = function(ccNum) {
var sum = 0;
for (var i=0; i<ccNum.length; i++ ) {
var eachLetter = ccNum.charAt(i);
if (!isNaN(eachLetter)) {
sum += +eachLetter;
}
}
return sum;
};
var ccNums = ["1234-2322-2343-2342","1234-2722-2343-2345", "1234-2722-2343-2842"];
var checkNums = [];
for (var i=0; i<ccNums.length; i++) {
var ccNum = ccNums[i];
var sum = addSum(ccNum);
console.log("The checksum of CC number:"+ccNum+" is "+sum);
checkNums.push(sum);
}
checkNums.sort(function(a,b) {
return b-a;
});
console.log(checkNums);
The solution using String.replace, String.split, Array.map, Array.filter and Array.reduce:
var ccNums = ["1234-2322-2343-2342","1234-2722-2343-2345", "1234-2722-2343-2842"],
getSum = function(num){
return num.replace("-", "").split("").map(Number).filter(Boolean).reduce(function(prev, next){
return prev + next;
});
};
ccNums.sort(function (a, b) {
return getSum(b) - getSum(a);
});
console.log(ccNums);
The output:
["1234-2722-2343-2842", "1234-2722-2343-2345", "1234-2322-2343-2342"]
I suggest use Sorting with map, because it uses only one iteration for the sum of a string and uses it until the sorts end. Then it rebuilds a new array with the sorted items.
var ccNums = ["1234-2322-2343-2342", "1234-2722-2343-2345", "1234-2722-2343-2842"];
// temporary array holds objects with position and sort-value
var mapped = ccNums.map(function (el, i) {
return {
index: i,
value: el.split('').reduce(function (r, a) { return r + (+a || 0); }, 0)
};
});
// sorting the mapped array containing the reduced values
mapped.sort(function (a, b) {
return b.value - a.value;
});
// container for the resulting order
var result = mapped.map(function (el) {
return ccNums[el.index];
});
console.log(result);
Use Array#sort with help of String#split and Array#reduce methods
var ccNums = ["1234-2322-2343-2342", "1234-2722-2343-2345", "1234-2722-2343-2842"];
// function to get sum of numbers in string
function sum(str) {
// split string
return str.split('-')
// iterate and get sum
.reduce(function(a, b) {
// parse string to convert to number
return a + Number(b); // in case string contains no-digit char that for avoiding NaN use "return a + ( parseInt(b, 10) || 0 )
}, 0); //set initial value to avoid 2 parsing
}
// call sort function
ccNums.sort(function(a, b) {
// find out sum and compare based on that
return sum(b) - sum(a);
});
console.log(ccNums)
Or much better way would be, store the sum in an object and refer in sort function which helps avoid calling sum function multiple times.
var ccNums = ["1234-2322-2343-2342", "1234-2722-2343-2345", "1234-2722-2343-2842"];
// function to get sum of numbers in string
function sum(str) {
// split string
return str.split('-')
// iterate and get sum
.reduce(function(a, b) {
// parse string to convert to number
return a + Number(b);
}, 0); //set initial value to avoid 2 parsing
}
var sumArr = {};
// create object for referncing sum,
// which helps to avoid calling sum function
// multiple tyms with same string
ccNums.forEach(function(v) {
sumArr[v] = sum(v);
});
// call sort function
ccNums.sort(function(a, b) {
// find out sum and compare based on that
return sumArr[b] - sumArr[a];
});
console.log(ccNums)

Currying a function that takes infinite arguments

Using ES5, how do you curry a function that takes infinite arguments.
function add(a, b, c) {
return a + b + c;
}
The function above takes only three arguments but we want our curried version to be able to take infinite arguments.
Hence, of all the following test cases should pass:
var test = add(1);
test(2); //should return 3
test(2,3); //should return 6
test(4,5,6); //should return 16
Here is the solution that I came up with:
function add(a, b, c) {
var args = Array.prototype.slice.call(arguments);
return function () {
var secondArgs = Array.prototype.slice.call(arguments);
var totalArguments = secondArgs.concat(args);
var sum = 0;
for (i = 0; i < totalArguments.length; i++) {
sum += totalArguments[0];
}
return sum;
}
}
However, I have been told that it's not very “functional” in style.
Part of the reason your add function is not very "functional" is because it is attempting to do more than just add up numbers passed to it. It would be confusing for other developers to look at your code, see an add function, and when they call it, get a function returned to them instead of the sum.
For example:
//Using your add function, I'm expecting 6
add(1,2,3) //Returns another function = confusing!
The functional approach
The functional approach would be to create a function that allows you to curry any other functions, and simplify your add function:
function curry(fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
return fn.apply(this, args.concat(
Array.prototype.slice.call(arguments, 0)
));
}
}
function add() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function (previousValue, currentValue) {
return previousValue + currentValue;
});
}
Now, if you want to curry this function, you would just do:
var curry1 = curry(add, 1);
console.log(
curry1(2), // Logs 3
curry1(2, 3), // Logs 6
curry1(4, 5, 6) // Logs 16
);
//You can do this with as many arguments as you want
var curry15 = curry(add, 1,2,3,4,5);
console.log(curry15(6,7,8,9)); // Logs 45
If I still want to add 1, 2, 3 up I can just do:
add(1,2,3) //Returns 6, AWESOME!
Continuing the functional approach
This code is now becoming reusable from everywhere.
You can use that curry function to make other curried function references without any additional hassle.
Sticking with the math theme, lets say we had a multiply function that multiplied all numbers passed to it:
function multiply() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function (previousValue, currentValue) {
return previousValue * currentValue;
});
}
multiply(2,4,8) // Returns 64
var curryMultiply2 = curry(multiply, 2);
curryMultiply2(4,8) // Returns 64
This functional currying approach allows you take that approach to any function, not just mathematical ones. Although the supplied curry function does not support all edge cases, it offers a functional, simple solution to your problem that can easily be built upon.
Method 1: Using partial
A simple solution would be to use partial as follows:
Function.prototype.partial = function () {
var args = Array.prototype.concat.apply([null], arguments);
return Function.prototype.bind.apply(this, args);
};
var test = add.partial(1);
alert(test(2)); // 3
alert(test(2,3)); // 6
alert(test(4,5,6)); // 16
function add() {
var sum = 0;
var length = arguments.length;
for (var i = 0; i < length; i++)
sum += arguments[i];
return sum;
}
Method 2: Single Level Currying
If you only want one level of currying then this is what I would do:
var test = add(1);
alert(test(2)); // 3
alert(test(2,3)); // 6
alert(test(4,5,6)); // 16
function add() {
var runningTotal = 0;
var length = arguments.length;
for (var i = 0; i < length; i++)
runningTotal += arguments[i];
return function () {
var sum = runningTotal;
var length = arguments.length;
for (var i = 0; i < length; i++)
sum += arguments[i];
return sum;
};
}
Method 3: Infinite Level Currying
Now, here's a more general solution with infinite levels of currying:
var add = running(0);
var test = add(1);
alert(+test(2)); // 3
alert(+test(2,3)); // 6
alert(+test(4,5,6)); // 16
function running(total) {
var summation = function () {
var sum = total;
var length = arguments.length;
for (var i = 0; i < length; i++)
sum += arguments[i];
return running(sum);
}
summation.valueOf = function () {
return total;
};
return summation;
}
A running total is the intermediate result of a summation. The running function returns another function which can be treated as a number (e.g. you can do 2 * running(21)). However, because it's also a function you can apply it (e.g. you can do running(21)(21)). It works because JavaScript uses the valueOf method to automatically coerce objects into primitives.
Furthermore, the function produced by running is recursively curried allowing you to apply it as many times to as many arguments as you wish.
var resultA = running(0);
var resultB = resultA(1,2);
var resultC = resultB(3,4,5);
var resultD = resultC(6,7,8,9);
alert(resultD + resultD(10)); // 100
function running(total) {
var summation = function () {
var sum = total;
var length = arguments.length;
for (var i = 0; i < length; i++)
sum += arguments[i];
return running(sum);
}
summation.valueOf = function () {
return total;
};
return summation;
}
The only thing you need to be aware of is that sometimes you need to manually coerce the result of running into a number by either applying the unary plus operator to it or calling its valueOf method directly.
Similar to the above problem. Sum of nth level curry by recursion
Trick: To stop the recursion I'm passing last () as blank**
function sum(num1) {
return (num2) => {
if(!num2) {
return num1;
}
return sum(num1 + num2);
}
}
console.log('Sum :', sum(1)(2)(3)(4)(5)(6)(7)(8)())
There is more generic approach by defining a curry function that takes minimum number of arguments when it evaluates the inner function. Let me use ES6 first (ES5 later), since it makes it more transparent:
var curry = (n, f, ...a) => a.length >= n
? f(...a)
: (...ia) => curry(n, f, ...[...a, ...ia]);
Then define a function that sums all arguments:
var sum = (...args) => args.reduce((a, b) => a + b);
then we can curry it, telling that it should wait until at least 2 arguments:
var add = curry(2, sum);
Then it all fits into place:
add(1, 2, 3) // returns 6
var add1 = add(1);
add1(2) // returns 3
add1(2,3) // returns 6
add1(4,5,6) // returns 16
You can even skip creating add by providing the first argument(s):
var add1 = curry(2, sum, 1);
ES5 version of curry is not as pretty for the lack of ... operator:
function curry(n, f) {
var a = [].slice.call(arguments, 2);
return a.length >= n
? f.apply(null, a)
: function () {
var ia = [].slice.call(arguments);
return curry.apply(null, [n, f].concat(a).concat(ia));
};
}
function sum() {
return [].slice.call(arguments).reduce(function (a, b) {
return a + b;
});
};
The rest is the same...
Note: If efficiency is a concern, you may not want to use slice on arguments, but copy it to a new array explicitly.
Bit late in this game, but here is my two cents. Basically this exploits the fact that functions are also objects in JavaScript.
function add(x) {
if (x === undefined) {
return add.numbers.reduce((acc, elem) => acc + elem, 0);
} else {
if (add.numbers) {
add.numbers.push(x);
} else {
add.numbers = [x];
}
}
return add;
}
Infinite sum with currying, you can pass a single parameter or multiple up-to infinite:
function adding(...arg) {
return function clousureReturn(...arg1) {
if (!arguments.length) {
let finalArr = [...arg, ...arg1];
let total = finalArr.reduce((sum, ele) => sum + ele);
return total;
}
return adding(...arg, ...arg1)
}
}
This is my solution for single level currying
function sum() {
let args = [...arguments];
let total = args.reduce((total,num) => total + num,0);
return total;
}
console.log(sum(1,2,3,4)) // 10
and the solution for infinite level currying
let sum= function (...args1) {
let total =args1.reduce((total,num) => total + num,0)
return function(...args2) {
if(args2.length!== 0) {
let total2 = args2.reduce((total,num)=>total + num,0);
return sum(total,total2);
}
return total;
};
};
console.log(sum(2,3,4)(2,3)(1)()); // 15
Simple solution
const add = (one) => { // one: Parameter passed in test
return (...args) => {
// args: Array with all the parameters passed in test
return one + args.reduce((sum, i) => sum + i, 0) // using reduce for doing sum
}
}
var test = add(1);
console.log(test(2)); //should return 3
console.log(test(2, 3)); //should return 6
console.log(test(4, 5, 6)); //should return 16

Compute value for different properties of object

Given an array of objects
function Example(x, y){
this.prop1 = x;
this.prop2 = y;
}
var exampleArray = new Array();
exampleArray.push(nex Example(0,1));
exampleArray.push(nex Example(1,3));
Now I would like to add a function which computes the average for one of the properties
function calcAvg(exampleArray, 'prop1') -> 0.5
function calcAvg(exampleArray, 'prop2') -> 2
If I don't want to use jQuery or other libraries, is there a generic way to do this?
Solution with Array.prototype.reduce method and check for valid property:
function Example(x, y) {
this.prop1 = x;
this.prop2 = y;
}
var exampleArray = new Array();
exampleArray.push(new Example(0, 1));
exampleArray.push(new Example(1, 3));
function calcAvg(arr, prop) {
if (typeof arr[0] === 'object' && !arr[0].hasOwnProperty(prop)) {
throw new Error(prop + " doesn't exist in objects within specified array!");
}
var avg = arr.reduce(function(prevObj, nextObj){
return prevObj[prop] + nextObj[prop];
});
return avg/arr.length;
}
console.log(calcAvg(exampleArray, 'prop2')); // output: 2
I think it will work ,
You need to iterate through all Example objects in the array and add the given property's value in a variable e.g. sum and then at the end divide it by total number of objects in the array to get average.
console.log(avg(exampleArray, 'prop1'));
function avg (array, propName){
var sum = 0;
array.forEach(function(exm){
sum+= exm[propName];
});
return sum / array.length;
}
You can use Array.prototype.reduce() for it.
The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
function Example(x, y) {
this.prop1 = x;
this.prop2 = y;
}
function calcAvg(array, key) {
return array.reduce(function (r, a) {
return r + a[key];
}, 0) / array.length;
}
var exampleArray = [new Example(0, 1), new Example(1, 3)],
avgProp1 = calcAvg(exampleArray, 'prop1'),
avgProp2 = calcAvg(exampleArray, 'prop2');
document.write(avgProp1 + '<br>');
document.write(avgProp2);
This code iterates over every value of arr, searches for property prop in every value, pushes the value of that property to an array named values and returns the sum of all the values in values divided by the number of values in it.
function calcAvg(arr,prop){
var values = [];
for(var i = 0; i<arr.length; i++){
values.push(arr[i][prop]);
}
var sum = values.reduce(function(prev,current){
return prev+current;
});
return sum/values.length;
}
Demo is here.

Functional approach to basic array construction

This is my code, acting upon myArray:
var myArray = [];
var i;
for(i = 0; i < 20; i += 1) {
myArray.push(Math.random());
}
Is there a functional equivalent of the above that does without the dummy variable i?
Favorite answers:
while(myArray.push(Math.random()) < 20);
$.map(Array(20), Math.random);
for(var myArray = []; myArray.push(Math.random()) < 20;);
Not in ES5, there's no real functional equivalent to it, as you have to have something which has an amount of 20 to apply map to...
var my20ElementArray = [0,1,2,3,4,5,6,7,8,9,10];
var myArray = my20ElementArray.map(Math.random);
You could create an xrange-like function what is in Python but that would just hide this "unused" variable inside a function.
With JavaScript 1.7, you can use Array comprehensions for this task:
var myArray = [Math.random() for each (i in range(0, 20))];
However, with ES5.1 you can just use the Array constructor to generate an array of arbitrary length, and then map it to random numbers. Only drawback is that map() does not work with uninitialised values, so I first generate an Array of empty strings by using join and split:
var myArray = new Array(20).join(" ").split(" ").map(Math.random);
Ugly, but short. A maybe better (but less understandable) idea from Creating range in JavaScript - strange syntax:
var myArray = Array.apply(null, {length: 20}).map(Math.random);
Starting with #FelixKlings comment, one could also use this one-liner without the i loop variable:
for (var myArray=[]; myArray.push(Math.random()) < 20;);
// much better:
for (var myArray=[]; myArray.length < 20;) myArray.push(Math.random());
Are you looking for something as follows:
function makeArray(length, def) {
var array = [];
var funct = typeof def === "function";
while (array.push(funct ? def() : def) < length);
return array;
}
Then you can create arrays as follows:
var array = makeArray(100); // an array of 100 elements
var zero = makeArray(5, 0); // an array of 5 `0`s
In your case you may do something like:
var myArray = makeArray(20, Math.random);
See the following fiddle: http://jsfiddle.net/WxtkF/3/
how about this?
it's functionale style and it's very concise.
var makeRandomArray = function(n){
if (n == 0) return [];
return [Math.random()].concat(makeRandomArray(n-1));
};
console.log(makeRandomArray(20))
http://jsfiddle.net/YQqGP/
​
You could try:
var myArray = String(Array(20)).split(',')
.map( () => Math.random() );
Or extend the Array prototype with something like:
Array.prototype.vector = function(n,fn){
fn = fn || function(){return '0';};
while (n--){
this.push(fn());
}
return this;
}
// usage
var myArray = [].vector(20, () => Math.random());
Or try something funny:
var myArray = function a(n,fn){
return n ? a(n-1,fn).concat(fn()) : [];
}(20, () => Math.random())
Or use Array.from (ES>=2015)
Array.from({length: 20}).map(() => Math.random())

Sampling a random subset from an array

What is a clean way of taking a random sample, without replacement from an array in javascript? So suppose there is an array
x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
and I want to randomly sample 5 unique values; i.e. generate a random subset of length 5. To generate one random sample one could do something like:
x[Math.floor(Math.random()*x.length)];
But if this is done multiple times, there is a risk of a grabbing the same entry multiple times.
I suggest shuffling a copy of the array using the Fisher-Yates shuffle and taking a slice:
function getRandomSubarray(arr, size) {
var shuffled = arr.slice(0), i = arr.length, temp, index;
while (i--) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(0, size);
}
var x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var fiveRandomMembers = getRandomSubarray(x, 5);
Note that this will not be the most efficient method for getting a small random subset of a large array because it shuffles the whole array unnecessarily. For better performance you could do a partial shuffle instead:
function getRandomSubarray(arr, size) {
var shuffled = arr.slice(0), i = arr.length, min = i - size, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}
A little late to the party but this could be solved with underscore's new sample method (underscore 1.5.2 - Sept 2013):
var x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
var randomFiveNumbers = _.sample(x, 5);
In my opinion, I do not think shuffling the entire deck necessary. You just need to make sure your sample is random not your deck. What you can do, is select the size amount from the front then swap each one in the sampling array with another position in it. So, if you allow replacement you get more and more shuffled.
function getRandom(length) { return Math.floor(Math.random()*(length)); }
function getRandomSample(array, size) {
var length = array.length;
for(var i = size; i--;) {
var index = getRandom(length);
var temp = array[index];
array[index] = array[i];
array[i] = temp;
}
return array.slice(0, size);
}
This algorithm is only 2*size steps, if you include the slice method, to select the random sample.
More Random
To make the sample more random, we can randomly select the starting point of the sample. But it is a little more expensive to get the sample.
function getRandomSample(array, size) {
var length = array.length, start = getRandom(length);
for(var i = size; i--;) {
var index = (start + i)%length, rindex = getRandom(length);
var temp = array[rindex];
array[rindex] = array[index];
array[index] = temp;
}
var end = start + size, sample = array.slice(start, end);
if(end > length)
sample = sample.concat(array.slice(0, end - length));
return sample;
}
What makes this more random is the fact that when you always just shuffling the front items you tend to not get them very often in the sample if the sampling array is large and the sample is small. This would not be a problem if the array was not supposed to always be the same. So, what this method does is change up this position where the shuffled region starts.
No Replacement
To not have to copy the sampling array and not worry about replacement, you can do the following but it does give you 3*size vs the 2*size.
function getRandomSample(array, size) {
var length = array.length, swaps = [], i = size, temp;
while(i--) {
var rindex = getRandom(length);
temp = array[rindex];
array[rindex] = array[i];
array[i] = temp;
swaps.push({ from: i, to: rindex });
}
var sample = array.slice(0, size);
// Put everything back.
i = size;
while(i--) {
var pop = swaps.pop();
temp = array[pop.from];
array[pop.from] = array[pop.to];
array[pop.to] = temp;
}
return sample;
}
No Replacement and More Random
To apply the algorithm that gave a little bit more random samples to the no replacement function:
function getRandomSample(array, size) {
var length = array.length, start = getRandom(length),
swaps = [], i = size, temp;
while(i--) {
var index = (start + i)%length, rindex = getRandom(length);
temp = array[rindex];
array[rindex] = array[index];
array[index] = temp;
swaps.push({ from: index, to: rindex });
}
var end = start + size, sample = array.slice(start, end);
if(end > length)
sample = sample.concat(array.slice(0, end - length));
// Put everything back.
i = size;
while(i--) {
var pop = swaps.pop();
temp = array[pop.from];
array[pop.from] = array[pop.to];
array[pop.to] = temp;
}
return sample;
}
Faster...
Like all of these post, this uses the Fisher-Yates Shuffle. But, I removed the over head of copying the array.
function getRandomSample(array, size) {
var r, i = array.length, end = i - size, temp, swaps = getRandomSample.swaps;
while (i-- > end) {
r = getRandom(i + 1);
temp = array[r];
array[r] = array[i];
array[i] = temp;
swaps.push(i);
swaps.push(r);
}
var sample = array.slice(end);
while(size--) {
i = swaps.pop();
r = swaps.pop();
temp = array[i];
array[i] = array[r];
array[r] = temp;
}
return sample;
}
getRandomSample.swaps = [];
Or... if you use underscore.js...
_und = require('underscore');
...
function sample(a, n) {
return _und.take(_und.shuffle(a), n);
}
Simple enough.
You can get a 5 elements sample by this way:
var sample = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
.map(a => [a,Math.random()])
.sort((a,b) => {return a[1] < b[1] ? -1 : 1;})
.slice(0,5)
.map(a => a[0]);
You can define it as a function to use in your code:
var randomSample = function(arr,num){ return arr.map(a => [a,Math.random()]).sort((a,b) => {return a[1] < b[1] ? -1 : 1;}).slice(0,num).map(a => a[0]); }
Or add it to the Array object itself:
Array.prototype.sample = function(num){ return this.map(a => [a,Math.random()]).sort((a,b) => {return a[1] < b[1] ? -1 : 1;}).slice(0,num).map(a => a[0]); };
if you want, you can separate the code for to have 2 functionalities (Shuffle and Sample):
Array.prototype.shuffle = function(){ return this.map(a => [a,Math.random()]).sort((a,b) => {return a[1] < b[1] ? -1 : 1;}).map(a => a[0]); };
Array.prototype.sample = function(num){ return this.shuffle().slice(0,num); };
While I strongly support using the Fisher-Yates Shuffle, as suggested by Tim Down, here's a very short method for achieving a random subset as requested, mathematically correct, including the empty set, and the given set itself.
Note solution depends on lodash / underscore:
Lodash v4
const _ = require('loadsh')
function subset(arr) {
return _.sampleSize(arr, _.random(arr.length))
}
Lodash v3
const _ = require('loadsh')
function subset(arr) {
return _.sample(arr, _.random(arr.length));
}
If you're using lodash the API changed in 4.x:
const oneItem = _.sample(arr);
const nItems = _.sampleSize(arr, n);
https://lodash.com/docs#sampleSize
A lot of these answers talk about cloning, shuffling, slicing the original array. I was curious why this helps from a entropy/distribution perspective.
I'm no expert but I did write a sample function using the indexes to avoid any array mutations — it does add to a Set though. I also don't know how the random distribution on this but the code was simple enough to I think warrant an answer here.
function sample(array, size = 1) {
const { floor, random } = Math;
let sampleSet = new Set();
for (let i = 0; i < size; i++) {
let index;
do { index = floor(random() * array.length); }
while (sampleSet.has(index));
sampleSet.add(index);
}
return [...sampleSet].map(i => array[i]);
}
const words = [
'confused', 'astonishing', 'mint', 'engine', 'team', 'cowardly', 'cooperative',
'repair', 'unwritten', 'detailed', 'fortunate', 'value', 'dogs', 'air', 'found',
'crooked', 'useless', 'treatment', 'surprise', 'hill', 'finger', 'pet',
'adjustment', 'alleged', 'income'
];
console.log(sample(words, 4));
Perhaps I am missing something, but it seems there is a solution that does not require the complexity or potential overhead of a shuffle:
function sample(array,size) {
const results = [],
sampled = {};
while(results.length<size && results.length<array.length) {
const index = Math.trunc(Math.random() * array.length);
if(!sampled[index]) {
results.push(array[index]);
sampled[index] = true;
}
}
return results;
}
Here is another implementation based on Fisher-Yates Shuffle. But this one is optimized for the case where the sample size is significantly smaller than the array length. This implementation doesn't scan the entire array nor allocates arrays as large as the original array. It uses sparse arrays to reduce memory allocation.
function getRandomSample(array, count) {
var indices = [];
var result = new Array(count);
for (let i = 0; i < count; i++ ) {
let j = Math.floor(Math.random() * (array.length - i) + i);
result[i] = array[indices[j] === undefined ? j : indices[j]];
indices[j] = indices[i] === undefined ? i : indices[i];
}
return result;
}
You can remove the elements from a copy of the array as you select them. Performance is probably not ideal, but it might be OK for what you need:
function getRandom(arr, size) {
var copy = arr.slice(0), rand = [];
for (var i = 0; i < size && i < copy.length; i++) {
var index = Math.floor(Math.random() * copy.length);
rand.push(copy.splice(index, 1)[0]);
}
return rand;
}
For very large arrays, it's more efficient to work with indexes rather than the members of the array.
This is what I ended up with after not finding anything I liked on this page.
/**
* Get a random subset of an array
* #param {Array} arr - Array to take a smaple of.
* #param {Number} sample_size - Size of sample to pull.
* #param {Boolean} return_indexes - If true, return indexes rather than members
* #returns {Array|Boolean} - An array containing random a subset of the members or indexes.
*/
function getArraySample(arr, sample_size, return_indexes = false) {
if(sample_size > arr.length) return false;
const sample_idxs = [];
const randomIndex = () => Math.floor(Math.random() * arr.length);
while(sample_size > sample_idxs.length){
let idx = randomIndex();
while(sample_idxs.includes(idx)) idx = randomIndex();
sample_idxs.push(idx);
}
sample_idxs.sort((a, b) => a > b ? 1 : -1);
if(return_indexes) return sample_idxs;
return sample_idxs.map(i => arr[i]);
}
My approach on this is to create a getRandomIndexes method that you can use to create an array of the indexes that you will pull from the main array. In this case, I added a simple logic to avoid the same index in the sample. this is how it works
const getRandomIndexes = (length, size) => {
const indexes = [];
const created = {};
while (indexes.length < size) {
const random = Math.floor(Math.random() * length);
if (!created[random]) {
indexes.push(random);
created[random] = true;
}
}
return indexes;
};
This function independently of whatever you have is going to give you an array of indexes that you can use to pull the values from your array of length length, so could be sampled by
const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
getRandomIndexes(myArray.length, 3).map(i => myArray[i])
Every time you call the method you are going to get a different sample of myArray. at this point, this solution is cool but could be even better to sample different sizes. if you want to do that you can use
getRandomIndexes(myArray.length, Math.ceil(Math.random() * 6)).map(i => myArray[i])
will give you a different sample size from 1-6 every time you call it.
I hope this has helped :D
Underscore.js is about 70kb. if you don't need all the extra crap, rando.js is only about 2kb (97% smaller), and it works like this:
console.log(randoSequence([8, 6, 7, 5, 3, 0, 9]).slice(-5));
<script src="https://randojs.com/2.0.0.js"></script>
You can see that it keeps track of the original indices by default in case two values are the same but you still care about which one was picked. If you don't need those, you can just add a map, like this:
console.log(randoSequence([8, 6, 7, 5, 3, 0, 9]).slice(-5).map((i) => i.value));
<script src="https://randojs.com/2.0.0.js"></script>
D3-array's shuffle uses the Fisher-Yeates shuffle algorithm to randomly re-order arrays. It is a mutating function - meaning that the original array is re-ordered in place, which is good for performance.
D3 is for the browser - it is more complicated to use with node.
https://github.com/d3/d3-array#shuffle
npm install d3-array
//import {shuffle} from "d3-array"
let x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
d3.shuffle(x)
console.log(x) // it is shuffled
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.0.0/d3.min.js"></script>
If you don't want to mutate the original array
let x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
let shuffled_x = d3.shuffle(x.slice()) //calling slice with no parameters returns a copy of the original array
console.log(x) // not shuffled
console.log(shuffled_x)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.0.0/d3.min.js"></script>

Categories