Array Methods! Which should i use?🤔
Published: 2023-02-12 20:55:01

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"]

```
.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]
```

👉️ To **remove** from the original array
.pop // _removes from the end of the array_

```
 const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();
//>> "Mango"
```
.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
```
.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']
```

👉️ Others
.reverse // _reverses the order of elements in the array_

```
var a = [3,5,7,8];
a.reverse(); // 8 7 5 3
```
.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]
```
.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]
```
###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
```

👉️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']
```
👉️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"
```

👉️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
 ]
*/
```

👉️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]
```
.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]
```

### 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
```

👉️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
```

### 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 }
```

### 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
```

👉️ 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
```
.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
```

### 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"
```

### 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
```

###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']
```


Thank you for reading 💗❤️