Wednesday, September 18, 2024

Main Array Functions in JavaScript

 


Here is a summary of some major array functions with examples in JavaScript.


Code snippet to define an example of an array

var persons = new Array(); var object = { name: "Mary", age:22, email: "mary@gmail.com"}; persons.push(object); object = { name: "Jack", age:25, email: "jack@gmail.com"}; persons.push(object); object = { name: "Bob", age:37, email: "bob@gmail.com"}; persons.push(object);


Function

Definition

Result Type

Code Snippet

Code Output

filter

Gets the elements satisfying the testing function

Array

const filtered_persons =

persons.filter(p => p.age < 30);

console.log(filtered_persons);

[{name: 'Mary', age: 22, email: 'mary@gmail.com'}, {name: 'Jack', age: 25, email: 'jack@gmail.com'}]

map

Gets elements that have a subset of the original elements’ properties

Array

const persons_name = persons.map(p => p.name);

console.log(persons_name);


['Mary', 'Jack', 'Bob']

join

Concatenates all array elements as a string with a separator

String

const joined_name =

persons.map(p => p.name).join(', ');

console.log(joined_name);

Mary, Jack, Bob

find

Returns the first element satisfying the testing function

object

const first_found =

persons.find(p => p.age < 30);

console.log(first_found);

{name: 'Mary', age: 22, email: 'mary@gmail.com'}

findIndex


number

const first_index =

persons.findIndex(p => p.age > 25);

console.log(first_index);

2

reduce

Reduces array elements to a single value after applying a custom function

It depends on the single value you want to get like number, string, etc.

const initAge = 0;

const sumAges = persons.reduce(

(accumulator, currentPerson) =>

accumulator + currentPerson.age,

initAge,

);

const meanAge = Math.round(sumAges/persons.length);

console.log(meanAge);

28

No comments:

Post a Comment

Blog Posts

Enhancing Performance of Java-Web Applications

Applications built with a Java back-end, a relational database (such as Oracle or MySQL), and a JavaScript-based front-end form a common and...