Javascript Array Methods

Ace your homework & exams now with Quizwiz!

Sort an array in random order (basic implementation)

Implementation: const points = [40, 100, 1, 5, 25, 10]; points.sort(function(){return 0.5 - Math.random()})

lastIndexOf()

What it does: Array.lastIndexOf() is the same as Array.indexOf(), but returns the position of the last occurrence of the specified element. Implementation: const fruits = ["Apple", "Orange", "Apple", "Mango"]; let position = fruits.lastIndexOf("Apple") + 1;

... (spread operator)

What it does: The ... operator expands an iterable (like an array) into more elements: Implementation: const q1 = ["Jan", "Feb", "Mar"]; const q2 = ["Apr", "May", "Jun"]; const q3 = ["Jul", "Aug", "Sep"]; const q4 = ["Oct", "Nov", "May"]; const year = [...q1, ...q2, ...q3, ...q4]; // [Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,May]

from()

What it does: The Array.from() method returns an Array object from any object with a length property or any iterable object. Implementation: Array.from("ABCDEFG");

keys()

What it does: The Array.keys() method returns an Array Iterator object with the keys of an array. Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; const keys = fruits.keys(); for (let x of keys) { text += x + "<br>"; }

entries()

What it does: The entries() method returns an Array Iterator object with key/value pairs: [0, "Banana"][1, "Orange"][2, "Apple"][3, "Mango"] The entries() method does not change the original array. Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; const f = fruits.entries(); for (let x of f) { document.getElementById("demo").innerHTML += x; }

every()

What it does: The every() method checks if all array values pass a test. This example checks if all array values are larger than 18: Implementation: const numbers = [45, 4, 9, 16, 25]; let allOver18 = numbers.every(myFunction); function myFunction(value, index, array) { return value > 18; } Returns false

filter()

What it does: The filter() method creates a new array with array elements that pass a test. This example creates a new array from elements with a value larger than 18: Implementation: const numbers = [45, 4, 9, 16, 25]; const over18 = numbers.filter(myFunction); function myFunction(value, index, array) { return value > 18; } Output: [45, 25]

find()

What it does: The find() method returns the value of the first array element that passes a test function. This example finds (returns the value of) the first element that is larger than 18: Implementation: const numbers = [4, 9, 16, 25, 29]; let first = numbers.find(myFunction); function myFunction(value, index, array) { return value > 18; }

flatMap()

What it does: The flatMap() method first maps all elements of an array and then creates a new array by flattening the array. Implementation: const myArr = [1, 2, 3, 4, 5, 6]; const newArr = myArr.flatMap((x) => x * 2); Output: [2,4,6,8,10,12}

forEach()

What it does: The forEach() method calls a function (a callback function) once for each array element. Implementation: const numbers = [45, 4, 9, 16, 25]; let txt = ""; numbers.forEach(myFunction); function myFunction(value, index, array) { txt += value + "<br>"; } Output: 45 4 9 16 25

indexOf()

What it does: The indexOf() method searches an array for an element value and returns its position. Note: The first item has position 0, the second item has position 1, and so on. Implementation: const fruits = ["Apple", "Orange", "Apple", "Mango"]; let position = fruits.indexOf("Apple") + 1;

map()

What it does: The map() method creates a new array by performing a function on each array element. The map() method does not execute the function for array elements without values. The map() method does not change the original array. Implementation: const numbers1 = [45, 4, 9, 16, 25]; const numbers2 = numbers1.map(myFunction); function myFunction(value, index, array) { return value * 2; }

reduce()

What it does: The reduce() method runs a function on each array element to produce (reduce it to) a single value. The reduce() method works from left-to-right in the array. See also reduceRight(). The reduce() method does not reduce the original array. This example finds the sum of all numbers in an array: Implementation: const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduce(myFunction); function myFunction(total, value, index, array) { return total + value; }

reduceRight()

What it does: The reduceRight() method runs a function on each array element to produce (reduce it to) a single value. The reduceRight() works from right-to-left in the array. See also reduce(). The reduceRight() method does not reduce the original array. This example finds the sum of all numbers in an array: Implementation: const numbers = [45, 4, 9, 16, 25]; let sum = numbers.reduceRight(myFunction); function myFunction(total, value, index, array) { return total + value; }

some()

What it does: The some() method checks if some array values pass a test. This example checks if some array values are larger than 18: Implementation: const numbers = [45, 4, 9, 16, 25]; let someOver18 = numbers.some(myFunction); function myFunction(value, index, array) { return value > 18; } Returns true

Changing or retrieving elements

What it does: Array elements are accessed using their index number Implementation: To change an element at a given index: const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[0] = "Kiwi"; To retrieve an element at a given index: const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits[0] returns Banana

delete()

What it does: Array elements can be deleted using the JavaScript operator delete. Using delete leaves undefined holes in the array. It is recommended to use push or pop instead Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits[0]; New fruits array = [undefined, "Orange", "Apple", "Mango"]

sort() for numbers

What it does: By default, the sort() function sorts values as strings. This works well for strings ("Apple" comes before "Banana"). However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1". Because of this, the sort() method will produce incorrect result when sorting numbers. You can fix this by providing a compare function Implementation: Ascending sort: const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); Descending sort: const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a});

includes()

What it does: ECMAScript 2016 introduced Array.includes() to arrays. This allows us to check if an element is present in an array (including NaN, unlike indexOf). Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.includes("Mango"); // is true

Sorting Object Arrays

What it does: Even if objects have properties of different data types, the sort() method can be used to sort the array. The solution is to write a compare function to compare the property value. Comparing string properties is a little more complex. Implementation: const cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010}]; //Comparing property values cars.sort(function(a, b){return a.year - b.year}); //Comparing string values cars.sort(function(a, b){ let x = a.type.toLowerCase(); let y = b.type.toLowerCase(); if (x < y) {return -1;} if (x > y) {return 1;} return 0;});

toString()

What it does: The JavaScript method toString() converts an array to a string of (comma separated) array values. Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; answer = fruits.toString(); Returns: Banana,Orange,Apple,Mango

The Fisher Yates Sorting Method

What it does: The basic use of array.sort(), is not accurate. It will favor some numbers over the others. The most popular correct method, is called the Fisher Yates shuffle, and was introduced in data science as early as 1938 Implementation: const points = [40, 100, 1, 5, 25, 10];for (let i = points.length -1; i > 0; i--) { let j = Math.floor(Math.random() * (i+1)); let k = points[i]; points[i] = points[j]; points[j] = k;}

concat()

What it does: The concat() method creates a new array by merging (concatenating) existing arrays. The concat() method can take any number of array arguments. The concat() method can also take strings as arguments. Implementation: Merging 2 arrays: const myGirls = ["Cecilie", "Lone"]; const myBoys = ["Emil", "Tobias", "Linus"]; const myChildren = myGirls.concat(myBoys); myChildren returns Cecilie,Lone,Emil,Tobias,Linus Merging 3 arrays: const arr1 = ["Cecilie", "Lone"];const arr2 = ["Emil", "Tobias", "Linus"];const arr3 = ["Robin", "Morgan"];const myChildren = arr1.concat(arr2, arr3); Taking strings as arguments: const arr1 = ["Emil", "Tobias", "Linus"]; const myChildren = arr1.concat("Peter");

flat()

What it does: The flat() method creates a new array with sub-array elements concatenated to a specified depth. Implementation: const myArr = [[1,2],[3,4],[5,6]]; const newArr = myArr.flat(); returns newArr: [1,2,3,4,5,6]

join()

What it does: The join() method also joins all array elements into a string. It behaves just like toString(), but in addition you can specify the separator Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; result = fruits.join(""); Returns: BananaOrangeAppleMango

length

What it does: The length property returns the length (size) of an array Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; let size = fruits.length;

pop()

What it does: The pop() method removes the last element from an array. The pop() method returns the value that was "popped out" Implementation: To remove an element without retrieving it: const fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.pop(); To return the removed element: const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.pop(); Return is "Mango"

push()

What it does: The push() method adds a new element to an array (at the end). The push() method returns the new array length. Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.push("Kiwi"); const fruits = ["Banana", "Orange", "Apple", "Mango"]; let length = fruits.push("Kiwi"); length = 5

reverse()

What it does: The reverse() method reverses the elements in an array. Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.reverse(); Result: Mango,Apple,Orange,Banana Note: In many cases, you'll want to sort the array first for this to be useful.

shift()

What it does: The shift() method removes the first array element and "shifts" all other elements to a lower index. The shift() method returns the value that was "shifted out". Implementation: To remove the first element with no return: const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift(); To retrieve the first element and remove it: const fruits = ["Banana", "Orange", "Apple", "Mango"]; let fruit = fruits.shift(); fruit = Banana

slice()

What it does: The slice() method slices out a piece of an array into a new array. The slice() method creates a new array. The slice() method does not remove any elements from the source array. The slice() method can take two arguments like slice(1, 3). The method then selects elements from the start argument, and up to (but not including) the end argument. Implementation: Slices from index 3 through the rest of the array: const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; const citrus = fruits.slice(3); With beginning and end argument: const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; const citrus = fruits.slice(1, 3);

sort()

What it does: The sort() method sorts an array alphabetically. Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); Result: Apple,Banana,Mango,Orange Note: sort() without additional parameters will only be useful for sorting strings.

splice()

What it does: The splice() method can be used to add new items to an array. The first parameter (2) defines the position where new elements should be added (spliced in). The second parameter (0) defines how many elements should be removed. The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added. The splice() method returns an array with the deleted items Implementation: The splice() method can be used to add new items to an array: const fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.splice(2, 0, "Lemon", "Kiwi"); Banana,Orange,Apple,Mango --> Banana,Orange,Lemon,Kiwi,Apple,Mango The splice() method returns an array with the deleted items: const fruits = ["Banana", "Orange", "Apple", "Mango"]; let newFruits = fruits.splice(2, 2, "Lemon", "Kiwi"); Original Array:Banana,Orange,Apple,Mango New Array:Banana,Orange,Lemon,Kiwi Removed Items:Apple,Mango Using splice() to Remove Elements const fruits = ["Banana", "Orange", "Apple", "Mango"];fruits.splice(0, 1);

unshift()

What it does: The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements. The unshift() method returns the new array length. Implementation: const fruits = ["Banana", "Orange", "Apple", "Mango"]; let length = fruits.unshift("Lemon");

Find the Lowest (or Highest) Array Value

What it does: There are no built-in functions for finding the max or min value in an array. However, after you have sorted an array, you can use the index to obtain the highest and lowest values. Sorting a whole array is a very inefficient method if you only want to find the highest (or lowest) value. Implementation: Sorting method: const points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); // now points[0] contains the lowest value // and points[points.length-1] contains the highest value Using Math.min() or Math.max(): function myArrayMax(arr) { return Math.max.apply(null, arr); } function myArrayMin(arr) { return Math.min.apply(null, arr); }


Related study sets

Google and the Right to Be Forgotten Case extras

View Set

MQM 220 Management Exam 5: Ch 17-20 (Fall 2015)

View Set

Forms Of Business & Formation Of Partnerships

View Set

SOCIAL AND DIGITAL MEDIA METRICS TEST 1

View Set

FINAL EXAM (Supply Chain Management)

View Set

Chapter 3- Types of Policies and Riders (STUDY)

View Set