Skip to content

Instantly share code, notes, and snippets.

@snowden-fu
Last active May 10, 2022 00:05
Show Gist options
  • Save snowden-fu/f942bbfb3680e800663b44d3923dd84f to your computer and use it in GitHub Desktop.
Save snowden-fu/f942bbfb3680e800663b44d3923dd84f to your computer and use it in GitHub Desktop.
Utilities function for JavaScript
/**
*
* @param {*} arr array to search
* @param {*} val single element to search in array
* @returns
*/
function findAllIndexesOf(arr, val) {
var indexes = [], i;
for(i = 0; i < arr.length; i++)
if (arr[i] === val)
indexes.push(i);
return indexes;
}
/**
* e.g.
*
* arr = [ 'a', ' ', 'b', 'c', 'b' ]
* val = 'b'
* getAllIndexes(arr, val)-> [ 2, 4 ]
*/
/**
*
* @param {number} length length of object
* @param {number} n length of index to generate
* @returns
*/
const randIdxArrayByLength = (length, n)=>{
const res = Array.from({length:n},(item, index)=> index).sort(() => Math.random() - 0.5).slice(0,n);
return res
}
// e.g.
// console.log(randIdxArrayByLength(5, 3));
// [ 1, 0, 2 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment