DEV Community

Mohammed Ali
Mohammed Ali

Posted on • Updated on

Array

Methods are fns which can be called on objects
Arrays are objects, hence they also have methods in JS.

slice(begin): extract part of array in a new array, without mutating the original array.

let arr = ['a','b','c','d','e'];

// Usecase: Extract till index passed as argument
arr.slice(2); // [ 'c', 'd', 'e' ]

// Usecase: Extract from [first index] to [second index-1] value.
arr.slice(2,4); // [ 'c', 'd' ] i.e Length of array will be end-begin or 4-2 = 2 

// Usecase: Extract last 2 elements
arr.slice(-2); // [ 'd', 'e' ]

// Usecase: Extract the last element.
arr.slice(-1);  // [ 'e' ]  

// Usecase: Extract from index passed to leaving the last two elements.
arr.slice(1,-2);  // [ 'e' ]  

// Usecase: Create a shallow copy of an array
arr.slice(); // 1st way
[...arr]; // 2nd way
Enter fullscreen mode Exit fullscreen mode

splice: mutates the original array

// splice: remove the elements begining from the index passed. Mutates the orig. array.
// returns: part of the removed array
let arr = ['a','b','c','d','e'];
// arr.splice(2); // [ 'c', 'd', 'e' ]
// arr; // [ 'a', 'b' ]

// Usecase: Remove last element of the array
// arr.splice(-1); // [ 'e' ]
// arr; // [ 'a', 'b', 'c', 'd' ]

// Usecase: Delete no of elements. splice(index, deleteCount)
arr.splice(1, 3); // [ 'b', 'c', 'd' ]
arr; // [ 'a', 'e' ]
Enter fullscreen mode Exit fullscreen mode

reverse: mutates the original array.

returns: reversed array

let arr = ['a','b','c','d','e'];
let arr2 = arr.reverse();
arr;
arr2;
Enter fullscreen mode Exit fullscreen mode

concat: joins two arrays.

returns: joined array

let arr1 = ['a','b','c','d','e'];
let arr2 = ['f','g','h','i','j'];

[...arr1, ...arr2];       // 1st way
arr2 = arr1.concat(arr2); // 2nd way
Enter fullscreen mode Exit fullscreen mode

join: joins two arrays.

returns: joined array

let arr1 = ['a','b','c','d','e'];
let arr2 = ['f','g','h','i','j'];
const x = arr1.concat(arr2);
x.join('-'); // 'a-b-c-d-e-f-g-h-i-j'
Enter fullscreen mode Exit fullscreen mode

"As time progresses, you'll remember them based on their usage."

at: starts counting from the end, begining with index as -1

Suports method chaining. Works on arrays, strings

let arr = ['a','b','c','d','e'];

arr[0];    // 1st way
arr.at(0); // 2nd way

// Get the last element of the array
arr[arr.length - 1];  // 1st way
arr.slice(-1)[0];     // 2nd way
arr.at(-1);           // 3rd way

arr.at(0); // 'a'
arr.at(-1); // 'e'
Enter fullscreen mode Exit fullscreen mode

forEach:

// Looping over array using forEach method.
let account = [2000,-300,+400, -200, -500, +1000, -300];

// Loop over an array using for-of
for(let money of account){
  if(money > 0){
    console.log(`Deposited ${money}`);
  } else {
    console.log(`Withdrawn ${Math.abs(money)}`);
  }
}

// .entries(): returns an array of arrays.
// return the output as index-value pair.
// first element must be index, second element must be element-value
for(let [i,money] of account.entries()){
  if(money > 0){
    console.log(`Transaction ${i+1}, Deposited ${money}`);
  } else {
    console.log(`Transaction ${i+1}, Withdrawn ${Math.abs(money)}`);
  }
}

// Loop over an array using forEach which requires a callback fn.
// forEach will call the callback fn, and not we.
// forEach will pass each element as argument in every iteration.
account.forEach(function(money){
  if(money > 0){
    console.log(`Deposited ${money}`);
  } else {
    console.log(`Withdrawn ${Math.abs(money)}`);
  }
});
// Iteration 1: pass arg1 to CB-fn(arg1)
// Iteration 2: pass arg2 to CB-fn(arg2)
// Iteration 3: pass arg3 to CB-fn(arg3)
// .....
// .....


// forEach will pass each element, index, array as argument in every iteration. Order of arguments matter, not the no of these arguments i.e first element should be the current-Element, second element should be index, third element should be entire array which is being looped-over.
// first element must be element-value, second element should be index, third element must be entire array. This is how its different from array.entries()
account.forEach(function(money, i, arr){
  if(money > 0){
    console.log(`Transaction ${i+1}, Deposited ${money} into ${arr}`);
  } else {
    console.log(`Transaction ${i+1}, Withdrawn ${Math.abs(money)} from ${arr}`);
  }
});
Enter fullscreen mode Exit fullscreen mode

When to use for-of & forEach:

forEach: Cannot break-out of it. continue-break don't work inside it. Will always loop over the entire array, and nothing can be done to stop it.
for-of: Used when we need to loop out of the array.

"As you practice more & more, you'll get better in your skills."

forEach

works on arrays as well as maps & sets also.
creates side-effect as compared to map().
elements are logged one by one.

// Map
const currencies = new Map([
  // key, value pairs inside map are listed below
  ['USD', 'United States Dollar'],
  ['EUR', 'Euro'],
  ['GBP', 'British Pound']
]);

// called with currentValue in the iteration i.e val, with its key & the entire map
currencies.forEach(function(val, key, map){
  console.log(`${key}: ${val}`);
})


// Set: Need to pass an iterable as arg to 'new Set()'
const currenciesUnique = new Set(['USD','GBP','USD','GBP','EUR', 'INR', 'CAD']);
console.log(currenciesUnique);

// A set neither has keys nor indexes. Hence, to make forEach common for all, the callback fn signature was left like that.
// _ in arg denotes a complete unnecessary variable as we cannot have redundant args name. 
currenciesUnique.forEach(function(val, _ , map){
  console.log(`${val}: ${val}`);
});

Enter fullscreen mode Exit fullscreen mode

map()

maps values from an existing array to a new array based on C/b.
similar to forEach, but it creates a brand new array.
takes an array, loops over it, apply Callback fn on each element.
map() will call the callback fn on each of the elements, not us.
Each time map() calls a callback, it passes element, index, whole array.
Side-effect is not created in each iteration of map() i.e elements are not logged one after another. All operations are completed, then the final result is logged.

const movements = [400, -200, 300, 500, -700, 100, -900];

// A new array is returned by map() without mutating the original array.
const eurToUsd = 1.1;
const movementsUSD = movements.map(mov => (mov*eurToUsd).toFixed(2));

movements;
movementsUSD;

// Manually creating a new array.
const movementsUSDfor = [];
for(const mov of movements){
  movementsUSDfor.push((mov * eurToUsd).toFixed(2));
}
movementsUSDfor;

const movementsDescriptions = movements.map((mov, i, arr) => {
  console.log(`Transaction ${i+1}: ${(mov>0)? 'Deposited' : 'Withdrawn'} ${Math.abs(mov)}`);  
});
movementsDescriptions;
Enter fullscreen mode Exit fullscreen mode

filter()

filter out the elements in a new array which satisfy the C/b condn.

const movements = [400, -200, 300, 500, -700, 100, -900];
// Fnal approach. Fns can be chained here.
const deposits = movements.filter(mov => {
  return mov>0;
});
deposits;

// Same result in both cases.
const depositFor = []
for(let mov of movements){
  if(mov>0){
    depositFor.push(mov);
  }
}
depositFor;

const withdrawls = movements.filter(mov => {
  return mov<0;
});
withdrawls;
Enter fullscreen mode Exit fullscreen mode

reduce()

reduces all elements down to a single value.
Ex. adding all elements together. Define an accumulator, keep adding the current element to the accumulator to get the resultant sum in the end.
this value is return from the method.

const movements = [400, -200, 300, -500, -700, 100, 900];

// Fnal approrach using .reduce()
// loops over array, calls the callback on each iteration.
// acc is current sum of all the prev values.
const balance = movements.reduce(function(acc, cur, i, arr){
  console.log(`Iteration ${i+1}: ${acc}`)
  return acc + cur;
}, 1000); // 1000 is the initial value of acc in the first iteration
balance;

// for-of approach
let balance2 = 1000;
for(let mov of movements){
  balance2 += mov;
}
balance2;


// Maximum Value
const balance = movements.reduce(function(acc, mov){
  if(acc > mov){
    return mov;
  } else{
    return mov;
  }
}, movements[0]); // 1000 is the initial value of acc in the first iteration
balance;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)