-
Notifications
You must be signed in to change notification settings - Fork 0
08 Array Methods
Biswajit Sundara edited this page May 1, 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);