Arrays Flashcards
What is an array?
An array is a chunk of contiguous memory that a program can access by using indices. Arrangement of boxes where a program can store values.
Insert the value ‘test’ at index 3 in to this array [0,1,2,3,4,5]?
function test(a, pos, val){ for(var i = arr.length - 1; i >= pos + 1; i–){ arr[i] = arr[i - 1]; } arr[pos] = val; return arr; }
How do you randomize an array of numbers?
For 0 to arr.length Generate random number between 0 and arr.length inclusive Swap arr[i] and arr[random]
Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.
chunk([“a”, “b”, “c”, “d”], 2) should return [[“a”, “b”], [“c”, “d”]].
function chunk(arr, size) { // Break it up. var result = []; for(var i = 0; i \< arr.length; i) { result.push(arr.slice(i, i+=size)) } return result; }
Bonfire: Mutations
Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.
mutation([“hello”, “hey”]) should return false.
mutation([“hello”, “Hello”]) should return true.
mutation([“zyxwvutsrqponmlkjihgfedcba”, “qrstu”]) should return true.
mutation([“Mary”, “Army”]) should return true.
mutation([“Mary”, “Aarmy”]) should return true.
mutation([“Alien”, “line”]) should return true.
mutation([“floor”, “for”]) should return true.
mutation([“hello”, “neo”]) should return false
function mutation(arr) { var str1 = arr[0].toLowerCase(); var str2 = arr[1].toLowerCase(); for(var i = 0; i \< str2.length; i++){ if(str1.indexOf(str2.charAt(i)) \< 0) { return false; } } return true; }
Remove all falsy values from an array.
Falsy values in javascript are false, null,0, “”, undefined, and NaN.
function bouncer(arr) { // Don't show a false ID to this bouncer. var result = []; arr.forEach(function(item){ if(Boolean(item)) { result.push(item); } }); return result; }
You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
destroyer([1, 2, 3, 1, 2, 3], 2, 3) should return [1, 1].
destroyer([1, 2, 3, 5, 1, 2, 3], 2, 3) should return[1, 5, 1].
destroyer([3, 5, 1, 2, 2], 2, 3, 5) should return [1].
destroyer([2, 3, 2, 3], 2, 3) should return [].
function destroyer(arr) { // Remove all the values var args = Array.prototype.slice.call(arguments, 1); return arr.filter(function(element, index){ return args.indexOf(element) === -1; }); }