Home Web Front-end JS Tutorial Commonly used Javascript Array Methods.

Commonly used Javascript Array Methods.

Jul 18, 2024 am 10:12 AM

Commonly used Javascript Array Methods.

In this post we will learn about commonly used Javascript array methods that uses iteration and callback function to archieve their functionality.

iteration refers to repeated execution of a set of statements or code blocks, which allows us to perform the same operation multiple times.

In simple terms, A callback is a function definition passed as an argument to another function.

To keep things simple, we will focus on these three point.

  1. When a particular array method should be used.
  2. What the array method returns.
  3. code example of the array method. **

Before we proceed let's understand how these array methods are structured.

// Array method(callback(the condition we want to execute on each item in our array))

Each of these array method is a function that recieves a callback as an argument, it is in this callback that we specify the conditions we want to execute on each of our array item.

We will be using this array of objects for our examples.

`const data = [
{
"userId": 1,
"username": "Francis",
"message": "Hey, how's it going?",
"timestamp": "2024-02-18T12:30:00Z",
"status": "online",
"messageSent": 28,
"role": "user",
"passCode": "293087O7764"

},
{
"userId": 2,
"username": "Moses",
"message": "Not bad, just working on a project.",
"timestamp": "2024-02-18T12:35:00Z",
"status": "away",
"messageSent": 74,
"role": "user",
"passCode": "675147O2234"
},
{
"userId": 3,
"username": "Vicky",
"message": "Hey folks! What's the latest gossip?",
"timestamp": "2024-02-18T12:40:00Z",
"status": "online",
"messageSent": 271,
"role": "moderator",
"passCode": "76352O8069"

},
{
"userId": 4,
"username": "Junior",
"message": "Not much, just chilling. How about you?",
"timestamp": "2024-02-18T12:45:00Z",
"status": "offline",
"messageSent": 125,
"role": "admin",
"passCode": "21876O3483"
}
]`

forEach: forEach is used when we want to execute a condition on all of our array items. forEach returns undefined.

function getMessageSent(users){
let sumMessageSent = 0;
users.forEach(function(user){
sumMessageSent += user.messageSent;
})
return sumMessageSent;
}
getMessageSent(data) // output: 498

reduce: reduce is used to reduce an array to a single value for example this array [8, 7, 3] can be reduced to the number 18. a reducer returns a single value.

The reducer function takes in two parameters first the reducer( which is made of the total and the current) and second the initialValue

The total : this is popularly called the accumulator. the total as i call it is the last computed value of the reducer function.

The current refers to a single array item. in our case we have four items(current).

The initialValue is the value we assign to the total on the first call. simply say the initalValue is the default value of the total

const getMessageSent = (users) => {
return users.reduce((total, current) => total += current.messageSent, 0)
}

getMessageSent(data) // output: 498

filter: Array.filter is used when we want to collect only items in the array that meet a specific condition. array.filter returns an array.

const onlineUsers = (users) => {
return users.filter(user => user.status === "online")
}

onlineUsers(data) // output: [object object]

find Array.find is used when we want to get only the first array Item that meet the condition defined inside the callback. array.find returns the first item NOT in an array but in the format of the item, in our case that will be an object or undefined if no match was found.

const getUserRole = (users) => {
return users.find(user => user.role === "user")
}

getUserRole(data) // output: {userId: 1, username: 'Francis', message: "Hey, how's it going?", timestamp: '2024-02-18T12:30:00Z', status: 'online', …}

Notice how only the first user that meets the conditon was returned.

map Array.map is used when we want to transform the items in the array. array.map returns an array of transformed items that satisfy the condition in our callback.

const getUserNameAndPass = (users) => {
return users.map((user) => {
const userPassCode = user.passCode.slice(-4);
return${user.username} ${userPassCode.padStart(
user.passCode.length,
"★"
)};
});
};

getUserNameAndPass(data)// output:['Francis ★★★★★★★7764', 'Moses ★★★★★★★2234', 'Vicky ★★★★★★8069', 'Junior ★★★★★★3483']

every array.every is used when we want check if all the array items passed our defined condition. array.every returns a boolean. true if all the items pass the condition and false if any of the items fail the condition.

const isOnline = data.every(user => dataItem.status === 'online')

console.log(isOnline) // output:false

Some array.some is used when we want to check that some of the array items pass a givin condition. array.some return a boolean. true if some of the items passed the condition and false if all of the item pass or fail.

const isOnline = data.every(user => dataItem.status === 'online')

console.log(isOnline) // output: true

These are some of the widly used array methods.

The above is the detailed content of Commonly used Javascript Array Methods.. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles