Array - patrickcole/learning GitHub Wiki
Array
- useful for storing groups of data together in a collection or list
Methods
Forward
Note 1: If your pattern is a more functional approach and using immutability; methods that return a new modified array are preferred over methods that actually mutate the existing array. Note 2: We will be showing methods that have callback functions using arrow methods
Map
Immutable method - will return a new modified array
Returns a brand new, modified array, based on the directive given inside the map
method:
const SALES_TAX = 0.05;
let withoutTax = [2,5,10];
let withTax = withoutTax.map(price => price + (price * SALES_TAX));
console.log(withTax);
// => [2.1, 5.25, 10.5]
// That was a really simple way to return a new array with 5% tax applied to each price
- The
map
method is also chainable, which means that the result of the map can then be sent to other methods such asfilter
,reduce
, etc.
Filter
Immutable method - will return a new modified array
Returns array of items, if any that pass the provided conditional:
const MAX_SPEND_LIMIT_PER_ITEM = 20;
let cart = [29,49,9,7,2];
let itemsForWorkParty = cart.filter(price => price <= MAX_SPEND_LIMIT_PER_ITEM);
console.log(itemsForWorkParty);
// => [9, 7, 2];
Reduce
Immutable method - will return a new value that has been reduced
Will run a provided method on each item in the array until it has been reduced down to a single returned value:
let itemsLeftInCart = [9,7,2];
let totalCost = itemsLeftInCart.reduce((amount, price) => amount + price);
console.log(totalCost); // => 18
ForEach
Does not return an array
- will loop through each item in the array
- not good use case for locating a value and then exiting the loop
let itemsInCart = ['Jacket', 'Hat', 'Pants'];
itemsInCart.forEach( item => console.log(item) );
// => 'Jacket'
// => 'Hat'
// => 'Pants'
Includes
- Will return a
Boolean
;true
if one of the values is equal to the expression:
let names = ['Patrick', 'James', 'Mark'];
console.log(names.includes('Patrick')); // => true
Some
- Will return a
Boolean
;true
if at least one of the values is found in the array:
let numbers = [1,5,9,16,7];
let containsEven = numbers.some(number => number % 2 === 0);
console.log(containsEven); // => true
Every
- Will return a
Boolean
;true
if all elements match expression:
let results = ['1',2,5,9,02];
let isNumbers = results.every(result => Number.isFinite(result));
console.log(isNumbers); // => false
// in this case the first value of '1' is a String
Sort
- Just using the sort command, as is, can lead to some unexpected results as sort will convert the values to strings, and with numbers, using unicode characters
- To resolve this, providing some context to the sort command can help smooth over these issues:
let numbers = [9,80,100];
console.log(numbers.sort()); // => [100,80,9];
// this is because 1 comes before 8, and 8 comes before 9
// even though *we* know 100 does not come before 80, etc..
// to fix this:
console.log(numbers.sort((a,b) => a - b)); // => [9,80,100];
What about objects with strings? The way to handle this is to convert strings to a comparable format using .toUpperCase()
and then compare their characters. We also need to advise the sort method on how to handle strings:
let topics = [
{ name: "JavaScript" },
{ name: "Arrays" },
{ name: "CSS" },
{ name: "SQL" }
];
let sortTopics = (a,b) => {
let topicA = a.name.toUpperCase();
let topicB = b.name.toUpperCase();
if ( topicA > topicB ) {
return 1;
}
if ( topicA < topicB ) {
return -1;
}
if ( topicA === topicB ) {
return 0;
}
}