-
Notifications
You must be signed in to change notification settings - Fork 0
08 Array Methods
Biswajit Sundara edited this page May 7, 2023
·
3 revisions
Below methods are available from ES6 and are not available in ES5.
The filter() method filters and extracts the element(s) of an array satisfying the provided condition. It doesn't change the original array.
let status=["Completed", "InProgress","Ordered","Completed","Ordered"];
let val="Completed";
let filtered=status.filter(function(item){
if(val===item)
return val;
});
console.log(filtered);
console.log(filtered[0]);The map() method will transform the array
let transformArray = [1,2,3,4].map((n)=>{
return n*n;
})
console.log(transformArray);Get the full name from the first and last names using map concept.
let persons = [
{firstname : "Malcom", lastname: "Reynolds"},
{firstname : "Kaylee", lastname: "Frye"},
{firstname : "Jayne", lastname: "Cobb"}
];
function getFullName(item) {
let fullname = [item.firstname,item.lastname].join(" ");
return fullname;
}
let fullnames= persons.map(getFullName);
console.log(fullnames);Let's say we have an array of amounts and want to add them all up.
const euros = [29.76, 41.85, 46.5];
const sum = euros.reduce((total, amount) => total + amount);
console.log(sum); This will print 118.11
- Array.find() and Array.findIndex() are two methods added to arrays in ES6
- This allows you to search for an element within an array based on a given criteria.
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
];
const user = users.find((user) => user.id === 2);
console.log(user); // Output: { id: 2, name: 'Bob' }
const index = users.findIndex((user) => user.id === 2);
console.log(index); // Output: 1For a string array
const fruits = ['Apple', 'Mango', 'Grapes'];
const index = fruits.findIndex((fruit)=> fruit==='Mango');
console.log(index);The built in sort method is ascending and converts elements to string and then does the sort.
- The array of strings can be sorted properly
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// Expected output: Array ["Dec", "Feb", "Jan", "March"]- The default
sort()method will produce weird result for numbers - That's because it will convert the numbers to strings and then do the sorting.
const array1 = [12, 6, 20, 5];
array1.sort();
console.log(array1);
// Expected: [5, 6, 12, 20], Actual: [ 12, 20, 5, 6 ]- Sorting array numbers correctly (ascending)
const numbers = [3, 1, 4, 2];
numbers.sort((a, b) => a - b );
console.log(numbers); // [4, 3, 2, 1]- Sorting array numbers correctly (descending)
const numbers = [3, 1, 4, 2];
numbers.sort((a, b) => b - a);
console.log(numbers); // [4, 3, 2, 1]- Sorting by attribute that's of number.
const people = [
{ name: "Alice", age: 32 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 42 },
{ name: "Dave", age: 18 },
];
const compareAge = (a, b) => a.age - b.age;
people.sort(compareAge);
console.log(people);- Sorting by attribute that's of string.
const people = [
{ name: "Alice", age: 32 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 42 },
{ name: "Dave", age: 18 },
];
const compareName = (a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
};
people.sort(compareName);
console.log(people);- If
a.name<b.namemeansacomes beforebthen return -1 - If
a.name>b.namemeansacomes afterbthen return 1 - If
a.nameis equal tob.name, then there's no difference in order, so return 0.
- It extracts a section of an array and returns a new array containing the selected elements.
- It does not modify the original array, but instead creates a new array with a shallow copy of the selected elements.
- Takes two arguments
start&end
const fruits = ["banana", "orange", "apple", "mango"];
const selectedFruits = fruits.slice(1, 3);
console.log(selectedFruits); // ["orange", "apple"]
console.log(fruits); // ["banana", "orange", "apple", "mango"]- Sort an array without modifying the original array
const fruits = ["banana", "orange", "apple", "mango"];
const sortedFruits = fruits.slice().sort();
console.log(sortedFruits); // ["apple", "banana", "mango", "orange"]
console.log(fruits); // ["banana", "orange", "apple", "mango"]- We can also use localCompare for comparing
const sortedFruits = fruits.slice().sort((a, b) => b.localeCompare(a));