USEFUL JAVASCRIPT ARRAY AND OBJECT METHODS

Kanchanabj
2 min readJan 29, 2021
  1. FILTER: creates a new array based on whether the items of an array pass a certain condition.

const studentsAge = [17, 16, 18, 19, 21, 17];

const ableToDrink = studentsAge.filter(age => age>18 );

//ableToDrink = [19,21]

2. MAP: creates a new array by manipulating the value in another array. It is great for data manipulation, it is immutable method.

const numbers = [2,3,4,5];

const dollars = numbers.map( number => ‘$’ + number);

//dollars [ ‘$2’, ‘$3’, ‘$4’, ‘$5’]

3.REDUCE: This method uses an accumulator to reduce all items in an array to a single value. great for calculating totals. The returned value can be of any type(i.e.object, array, string, integer).

const numbers = [5,10,15];

const total = numbers.reduce(accumulator, currentValue) => accumulator +currentValue);

//output total = 30;

4.FOREACH: Applies a function on each item in an array. The foreach method executes provided function once for each element.

const emotions = [‘happy’, ‘sad’, ‘angry’]

emotions.forEach( emotion => console.log(emotion));

//output

‘happy’ ‘sad’ ‘angry’

5.SOME: The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.

const user = [‘user’, ‘user’, ‘user’, ‘admin’]

const containsAdmin = user.some(element => element ===’admin’)

//output: containsAdmin will be equal to true

6.EVERY: The every() method tests whether all element in the array pass the test implemented by the provided function. It returns a Boolean value.

const ratings = [3,4,5,3,5];

const goodRating = ratings.every(rating => rating>=3 );

//output: goodRating will be true

7.INCLUDES: The includes() method determines whether an array includes certain value among its entries, returns Boolean.

const names = [‘Sophie’, ‘George’, ‘waldo’];

const includesWaldo = names. Includes(‘waldo’);

//output : True

--

--