DEV Community

Cybermaxi7
Cybermaxi7

Posted on

Array Methods! Which should i use?🤔

We've got alot of array methods but the big question is which should i use?

The first question to ask yourself is what do i really wanna do with this array....

Let's consider some of this questions.

I want to mutate the array

To mutate an array simply means to change the original array

👉️ To add to the original array
.push // adds to the end of the array

const animals = ['pigs', 'goats', 'sheep'];

const count = animals.push('cows');
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

Enter fullscreen mode Exit fullscreen mode

.unshift // adds to the start of the array

let arr = [4, 5, 6];

arr.unshift(1, 2, 3);
console.log(arr);
// [1, 2, 3, 4, 5, 6]

arr = [4, 5, 6]; // resetting the array

arr.unshift(1);
arr.unshift(2);
arr.unshift(3);

console.log(arr);
// [3, 2, 1, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

👉️ To remove from the original array
.pop // removes from the end of the array

 const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
//>> "Mango"
Enter fullscreen mode Exit fullscreen mode

.shift // removes from the start of the array

const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
Enter fullscreen mode Exit fullscreen mode

.splice // removes any value of the array

let arr = ['foo', 'bar', 10, 'qux'];

// arr.splice(<index>, <steps>, [elements ...]);

arr.splice(1, 1);           // Removes 1 item at index 1
// => ['foo', 10, 'qux']

arr.splice(2, 1, 'tmp');    // Replaces 1 item at index 2 with 'tmp'
// => ['foo', 10, 'tmp']

arr.splice(0, 1, 'x', 'y'); // Inserts 'x' and 'y' replacing 1 item at index 0
// => ['x', 'y', 10, 'tmp']
Enter fullscreen mode Exit fullscreen mode

👉️ Others
.reverse // reverses the order of elements in the array

var a = [3,5,7,8];
a.reverse(); // 8 7 5 3
Enter fullscreen mode Exit fullscreen mode

.sort // sorts elements of an array in place

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]
const numbers = [3, 1, 4, 1, 5];
const sorted = numbers.sort((a, b) => a - b);
// numbers and sorted are both [1, 1, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

.fill // fills the array with a given static value

const array1 = [1, 2, 3, 4];

// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// expected output: [1, 2, 0, 0]

// fill with 5 from position 1
console.log(array1.fill(5, 1));
// expected output: [1, 5, 5, 5]

console.log(array1.fill(6));
// expected output: [6, 6, 6, 6]
Enter fullscreen mode Exit fullscreen mode

I want to create a new array

👉️Computed from original
.map // to loop through the array and create another array

var arr=[2,4,6];  
var result=arr.map(x=>x*3);  // 6, 12, 18
Enter fullscreen mode Exit fullscreen mode

👉️Filtered using Conditions
.filter //Filters an array based on the given conditions that returns a boolean value

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length < 6);

console.log(result);

//OUTPUT: ['spray', 'limit', 'elite']
Enter fullscreen mode Exit fullscreen mode

👉️Portion of the original array
.slice // returns selected elements of an array as a new array

const str = 'The quick brown fox jumps over the lazy dog.';

console.log(str.slice(31));
// expected output: "the lazy dog."

console.log(str.slice(4, 19));
// expected output: "quick brown fox"

console.log(str.slice(-4));
// expected output: "dog."

console.log(str.slice(-9, -5));
// expected output: "lazy"

console.log(str.slice(0, 2)); 
// expected output: "the"
Enter fullscreen mode Exit fullscreen mode

👉️Adding original array to another array
.concat //combines an two arrays and forms a new array containing both

const num1 = [2, 4, 5, 3, 8, 9, 11, 33, 44];
const num2 = [22, 33, 44, 55, 66, 77, 88];

const concatNumbers = num1.concat(num2)
console.log(concatNumbers)
//Expected output:
/*[
2, 4, 5, 3, 8, 9, 11, 33, 44, 22, 33, 44, 55, 66, 77, 88
 ]
*/
Enter fullscreen mode Exit fullscreen mode

👉️Flattening the array
Flattening an array is a process of reducing the dimensionality of an array.
.flat // creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

var arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

.flatMap // first maps each element in an array using a mapping function and then flattens the results into a new array.

var arr = [1, 2, 3, 4];

arr.flatMap(x => [x, x * 2]);
// is equivalent to
arr.reduce((acc, x) => acc.concat([x, x * 2]), []);
// [1, 2, 2, 4, 3, 6, 4, 8]
Enter fullscreen mode Exit fullscreen mode

To get an array index

👉️Based on value
.indexOf // returns the first index (position) of a specified value

let text = "Hello world, welcome to the universe.";
let result = text.indexOf("welcome"); // 13
Enter fullscreen mode Exit fullscreen mode

👉️Based on condition
.findIndex // returns the index of the first element in array that satisfies the given testing function

const array1 = [5, 12, 50, 130, 44];

const isLarger = (element) => element > 45 ;

const found = array1.findIndex(isLarger);

console.log(found);
//output = 2
Enter fullscreen mode Exit fullscreen mode

To get an array element

👉️Based on test condition
.find // _ returns the value of the first element that passes a test._

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'cherries', quantity: 8}
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
  {name: 'cherries', quantity: 15}

];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }
Enter fullscreen mode Exit fullscreen mode

To know if an array Includes

👉️ Based on value
.includes // determines whether an array includes a certain value among its entries, returning true or false as appropriate

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// output: true
Enter fullscreen mode Exit fullscreen mode

👉️ Based on test conditions
.some // checks whether at least one of the elements of the array satisfies the given condition or not

const fruits = ['apple', 'banana', 'mango', 'guava'];

function checkAvailability(arr, val) {
  return arr.some(function(arrVal) {
    return val === arrVal;
  });
}

checkAvailability(fruits, 'kela');   // false
checkAvailability(fruits, 'banana'); // true
Enter fullscreen mode Exit fullscreen mode

.every // returns true if the function returns true for all elements.

let numbers = [1, 2, 3, 42, 3, 2, 4, -1];

let allPassed = numbers.every(function(element){
    return element > 0;
});

// This method returns a Boolean value
// allPassed is set to false because not all elements were greater than 0
Enter fullscreen mode Exit fullscreen mode

To get a new string

👉️Based on separator string
.join // used to join the elements of an array into a string, the separator will be as specified in the method

const elements = ['Sun', 'Earth', 'Moon'];

console.log(elements.join());
// output: "Sun,Earth,Moon"

console.log(elements.join(''));
// output: "SunEarthMoon"

console.log(elements.join('-'));
// output: "Sun-Earth-Moon"
Enter fullscreen mode Exit fullscreen mode

To transform to value

👉️ Based on accumulator
.reduce // Boils down array to a single value of an type, number, string, boolean, strinf or even a new array or object

var array = [36, 25, 6, 15];

array.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue;
}, 0); // 36 + 25 + 6 + 15 = 82
Enter fullscreen mode Exit fullscreen mode

To just loop an array

👉️ .forEach // Iterates over the elements of the array

let colors = ['red', 'blue', 'green'];
// idx and sourceArr optional; sourceArr == colors
colors.forEach(function(color, idx, sourceArr) {
    console.log(color, idx, sourceArr)
});
// Output:
// red 0 ['red', 'blue', 'green']
// blue 1 ['red', 'blue', 'green']
// green 2 ['red', 'blue', 'green']
Enter fullscreen mode Exit fullscreen mode

Thank you for reading 💗❤️

Top comments (0)