Hello guys!
Today I'm here to show you some of my notes when learning array manipulation in JS!
Array functions
There are some functions to manipulate an array in JavaScript, the most used ones are:
☄️ array.push():
This method adds some data into an array, like:
const array = [1, 2, 3];
array.push(4);
console.log(array); // 1, 2, 3, 4
💥 array.pop():
This method removes the last item from the array:
const fruits = ['mango', 'apple', 'strawberry'];
fruits.pop();
console.log(fruits) // 'mango', 'apple'
🔪 array.splice(index, n):
This method starts removing items after the defined index, like:
const animals = ['elephant', 'dog', 'cat', 'giraffe'];
animals.splice(2,1);
console.log(animals); // 'elephant', 'dog', 'giraffe' it removed 1 item, as defined in the function
It can remove the amount of items defined into it:
const animals = ['elephant', 'dog', 'cat', 'giraffe'];
animals.splice(1,2);
console.log(animals); // 'elephant', 'giraffe' now it removed 2 items, starting from index 1
➕ array.concat(data):
This method can concat data into an array, like:
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
arr1.concat(arr2);
console.log(arr1); // 1, 2, 3, 4, 5, 6
🔎 array.indexOf(n):
This method returns the index of an item in the array:
const animals = ['elephant', 'dog', 'cat', 'giraffe'];
console.log(animals.indexOf('dog')); // 1
🆕 array.map(callbackFunction):
This method is used for creating a new array from another with the provided function, like:
const numbers = [1, 2, 3, 4];
const double = array.map((num) => num * 2);
console.log(double) // 2, 4, 6, 8
🫂 array.join(separator):
This method joins all elements of an array into a string with the specified separator, like:
const words = ['Hello', 'world', '!'];
const joinedString = array.join(' ');
console.log(joinedString) // 'Hello world !'
🧐 array.find(callbackFunction):
This method returns the value of the first element in the array that satisfies the provided testing function, like:
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
];
const user = array.find((user) => user.id === 2);
console.log(user) // { id: 2, name: 'Bob' }
🧐 array.includes(value):
This method determines whether an array includes a certain value among its entries, returning a Boolean, like:
const numbers = [1, 2, 3, 4, 5];
const includesThree = array.includes(3);
console.log(includesThree) // true
🥽 array.flat(depth):
This method creates a new array with all sub-array elements concatenated recursively up to the specified depth, like:
const nestedArray = [1, [2, [3, [4]]]];
const flattenedArray = array.flat(2);
console.log(flattenedArray) // 1, 2, 3, [4]
Hope you guys liked it!
Did i miss something?
Tell me your opinion on the replies!
Feel free to complement this article!
Good coding!
Top comments (0)