PedroGeoGISdev
  • Home
  • Linux OS
    • Linux: concepts
    • Linux: basic concepts
    • Linux: Bash
    • Linux: su and sudo
    • Linux: pipes
    • Linux: File System
    • Linux: Virtual Machines

    • Linux: distros
    • Linux Distros: Ubuntu
    • Linux Distros: Mint
    • Linux Distros: Debian
    • Linux Distros: openSuse
    • Linux Distros: Manjaro
    • Linux Distros: Red Hat Enterprise

    • Linux: laboratories
    • Linux Lab#LI01-1: Choose Linux
    • Linux Lab#LI01-2: Install at least three distributions
    • Linux Lab#LI01-3: Adjust user permissions
    • Linux Lab#LI02-1: Export env user with grep and pipe
    • Linux Lab#LI03-1: Manage users and groups
    • Linux Lab#LI03-2: Manage files
    • Linux Lab#LI03-3: Manage software
    • Linux Lab#LI03-4: Manage hardware
    • Linux Lab#LI04-1: Bash scripting, qtool
    • Linux Lab#LI04-2: Bash scripts as terminal tool
    • Linux Lab#LI04-3: Distribute the terminal app

    • Linux readings
    • Linux Resources
  • DevOps
    • What is DevOps
    • DevOps: Introduction
    • DevOps: Agile and Microservices
    • Infrastructure as code (IaC)
    • Immutable Infrastructure
    • Software Lifecycle

    • Documentation
    • How to document: Quarto and Obsidian

    • Network protocols
    • Network: Basics
    • Network: Client-server
    • Network Protocols
    • Network: DNS
    • Network: API Rest
    • Network: gRPC
    • Network: Websocket
    • Network: SMTP
    • Network: Ping
    • Network: UDP
    • Network: webhook
    • Network: SOAP
    • Network: graphQL

    • Version Control
    • Git
    • GitHub
    • Idea and GitHub 2023
    • Git and GitHub 2023 CLI

    • IDEs
    • IDE: Visual Code
    • IDE: IntellJIdea

    • DevOps tools
    • Amazon Web Services AWS
    • Docker
    • Jenkins pipelines
    • Kubernetes k8s
    • Digital Ocean
    • Nagios
    • Ansible

    • DevOps Laboratories
    • Lab 1: chat App
    • Lab 2: Spring Boot AWS AEB manually
    • Lab 3: Spring Boot and AWS S3 publisher
    • Lab 4: Spring Boot Docker/Jenkins
    • Lab 5: k8s on Digital Ocean
    • Lab 6: Spring Boot AWS codecommit

    • DevOps readings
    • DevOps Resources
  • MarkUp
    • MarkUp Languages
    • Introduction Markup
    • HTML Markup
    • Markdown Markup
    • Markdown and HTML working together, good idea?

    • Quarto Markdown
    • Quarto Markdown: basics
    • Quarto Markdown: creating
    • Quarto Markdown: publishing
    • Quarto Markdown: code & data
    • Quarto Markdown: api rest call
    • Quarto Markdown: OJS Cells
    • Quarto Markdown: cheat-sheet

    • Styling: CSS
    • Cascade Style Sheet
    • Cascade Style Sheet: Box Model and Containers
    • CSS: W3.css

    • MarkUp Languages Laboratories
    • Lab#MD01-1: Create and publish by Quarto

    • MarkUp Languages readings
    • MarkUp Languages Resources
  • Java SE
    • What is Java SE
    • Java Standard Edition: Basics
    • Java Standard Edition: Principles
    • Java MOOC Helsinki
    • Java MOOC Helsinki Syllabus

    • Java Create Project
    • Java SE: Maven
    • Java SE: Create Maven Project
    • Java SE: Project push GitHub
    • Java SE: JUnit and TDD

    • Java Concepts
    • Java SE: Class and Objects
    • Java SE: Scope
    • Java SE: static modifier
    • Java SE: Coupling and DDD
    • Java SE: Packages
    • Java SE: Abstract/Interface
    • Java SE: Java 8

    • Java Principles
    • Java SE: Encapsulation
    • Java SE: Abstraction
    • Java SE: Inherence
    • Java SE: Polymorphism

    • Java Design Patterns
    • Java Patterns: UML
    • Java Patterns: Types
    • Singleton
    • Factory
    • Abstract Factory
    • Builder
    • Facade
    • Bridge
    • Decorator
    • Composite
    • Observer
    • Strategy
    • State
    • Commander

    • Java SE Laboratories
    • Lab#SE00-1: Maven Person
    • Lab#SE00-2: Maven Clinic
    • Lab#SE00-3: Library Model
    • Lab#SE00-4: Abstract/Interface Human
    • Lab#SE01-1: Maven/Gradle Person and Account
    • Lab#SE01-2: Maven/Gradle Person and Account stored in JSON
    • Lab#SE02-1: Movie/Review, Model
    • Lab#SE02-2: Movie/Review, CRUD Operations
    • Lab#SE02-3: Movie/Review, factory
    • Lab#SE02-4: Movie/Review, interactivity and coupling
    • Lab#SE02-5: Movie/Review, simulate interactivity by console
    • Lab#SE03-1: Library/Book, Core-Model
    • Lab#SE03-2: Library/Book, Sprint Zero
    • Lab#SE03-3: Library/Book, Expand Model
    • Lab#SE04-1: healthyFood Restaurant, Core Model

    • Java SE readings
    • Java SE Resources
  • Python
    • Python Basics
    • Python: Basic Concepts
    • Python: Numbers
    • Python: Strings
    • Python: Conditionals
    • Python: Lists and Loops
    • Python: Nested Loops
    • Python: Tuples
    • Python: Sets
    • Python: Dictionaries
    • Python: Functions
    • Python: Higher-order Functions
    • Python: Variable Scope
    • Python: Variable Assigment
    • Python: None keyword in Python
    • Python: Object Oriented Programming (OOP)
    • Python: Inheritance and Polymorphism
    • Python: Encapsulation
    • Python: Abstraction
    • Python: Cheat-Sheets
  • JavaScript
    • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

    • React Framework

    • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

    • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

    • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

    • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

    • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

    • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios
    • Lab#RE02-1: Router & Hooks
    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management
    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS
    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front
    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request
    • Lab#RE07-1: traffic lights simulation

    • React JS readings
    • ReactJS Resources
  • Backend
    • Spring Legacy
    • Spring Framework
    • Spring MVC
    • Springs Servlets

    • Spring Boot Basics
    • Spring Boot: fundamentals
    • Spring Boot: create a Project
    • Spring Boot: H2 DB and Thymeleaf
    • Spring Boot: cycle

    • Spring Boot Concepts
    • Spring Boot: Dependency Injection
    • Spring Boot: Annotations
    • Spring Boot: Controller
    • Spring Boot: View
    • Spring Boot: Thymeleaf
    • Spring Boot: Vaadin Flow
    • Spring Boot: Vaadin Hilla
    • Spring Boot: Model
    • Spring Boot: Rest
    • Spring Boot: Data & DB
    • Spring Boot: JPA & DI
    • Spring Boot: JPA Mappings
    • Spring Boot: JPA Relationships
    • Spring Boot: JPA Queries
    • Spring Boot: JPA Inherence
    • Spring Boot: Scaling

    • Spring Boot Laboratories
    • Lab#SB00-1: Library UML
    • Lab#SB00-2: CRUD User
    • Lab#SB00-3: LibraryManagement
    • Lab#SB00-4: API Rest
    • Lab#SB00-5: Rest & JPA-H2
    • Lab#SB00-6: Rest & MongoDB
    • Lab#SB00-7: Styling
    • Lab#SB01-1: DataBase
    • Lab#SB02-1: JPA Relationships
    • Lab#SB03-1: APIs & cloud
    • Lab#SB04-1: JPA Inherence
    • Lab#SB05-1: API Rest
    • Lab#SB06-1: employeeCourse
    • Lab#SB07-1: monitor Book
    • Lab#SB08-1: Restaurant UML
    • Lab#SB08-2: Vaadin
    • Lab#SB08-3: H2 and API Rest
    • Lab#SB08-4: JPA
    • Lab#SB08-5: Test API Rest
    • Lab#SB09-1: SpringIO Conference

    • Spring Boot readings
    • Spring Boot Resources
  • Learning
    • Vocabulary
    • General Vocabulary
    • SCRUM Vocabulary
    • DevOps Vocabulary
    • Java SE Vocabulay
    • Spring Boot Vocabulary
    • DataBase Vocabulary
    • ReactJS Vocabulary
    • Web Vocabulary

    • Learning
    • Useful Questions
    • Learning: tips
    • Writing
    • Taking Notes
    • Comments
    • Document
    • Auto-Evaluate

    • Books & Articles
    • Books
    • Articles

    • What is SCRUM
    • SCRUM Agile Methodology
    • Agile Manifesto & Values
    • SCRUM Guide

    • Scrum Steps
    • Meetings, Impediments and Iterations
    • User stories, Tasks and Habits
    • Delivering Value & Communication
    • ScrumMaster, how it works
    • Mindset, the key to everything
    • Product Owner, how it works
    • Managing Time & Mind
    • Team & the Specialist
    • Albertus’ Dilemma
    • Before SCRUM
    • Team Dynamics
    • Emotions and Thoughts
    • Decision Making and Intuition
    • Beyond SCRUM
    • Balances, atmosphere and tools

    • Resources
    • SCRUM Resources
  • QGIS
    • QGIS basics
    • QGIS: basic concepts

    • QGIS laboratories
    • QGIS Laboratory 1: Introduction to Open Source GIS
  • ArcGIS Pro
    • ArcGIS Pro basics
    • ArcGIS Pro: basic concepts

    • ArcGIS Pro laboratories
    • ArcGIS Pro Laboratory 1: Getting Started
  • Bookmarks
    • Online Resources
    • Online Resources
  • About
    • About me and this site
    • About me
    • About this site
    • About images credit
  • Maps
  • Featured Projects
    • ✈️ Flight tracker
    • 🧑 People tracker
    • 🚗 Renting Car
    • Email
    • GitHub
    • LinkedIn
  1. JavaScript Basics
  2. JavaScript: Arrays
  • JavaScript

  • JavaScript Basics
    • JavaScript: Fundamentals
    • JavaScript: Data Types
    • JavaScript: Variables
    • JavaScript: Operators
    • JavaScript: Conditionals
    • JavaScript: Loops
    • JavaScript: Functions
    • JavaScript: Arrays
    • JavaScript: Objects

  • React Framework

  • ReactJS: Principles
    • React JS: Introduction
    • React JS: render virtual DOM
    • React JS: Create a React project
    • React JS: Components
    • React JS: JSX
    • React JS: props and state

  • JavaScript: web scripting
    • JavaScript: basics
    • JavaScript: functions
    • JavaScript: objects
    • JavaScript: variables
    • JavaScript: flux control

  • ES6: ECMAScript 6
    • React JS ES6: arrow functions
    • React JS ES6: import modules
    • React JS ES6: array, data and key
    • React JS ES6: destructuring
    • React JS ES6: spread operator

  • ReacJS 18: Hooks
    • React JS: Rules of Hooks
    • ReactJS: useState
    • React JS: useReducer
    • React JS: useRef
    • React JS: useEffect
    • React JS: useContext
    • ReactJS: useMemo
    • ReactJS: custom hooks

  • ReactJS: Designing an App
    • React JS App: async
    • React JS App: events
    • React JS App: router
    • React JS App: conditional render
    • React JS App: styling

  • React JS: Laboratories
    • Lab#RE01-1: API Rest Axios

    • Lab#RE02-1: Router & Hooks

    • Lab#RE03-1: to-do app
    • Lab#RE03-2: HighCharts
    • Lab#RE03-3: API Rest Mono
    • Lab#RE03-4: API Rest Domains
    • Lab#RE03-5: data management

    • Lab#RE04-1: todo & server
    • Lab#RE04-2: Spring Boot & ReactJS

    • Lab#RE05-1: chat & websockets
    • Lab#RE05-2: chat: backend
    • Lab#RE05-3: chat & AWS
    • Lab#RE05-4: chat: test ws AWS
    • Lab#RE05-5: chat & front
    • Lab#RE05-6: chat & ws: front

    • Lab#RE06-1: healthyFood Restaurant
    • Lab#RE06-1-PR: create a pull request

    • Lab#RE07-1: traffic lights simulation

  • React JS readings
    • ReactJS Resources

On this page

  • 1 Overview
  • 2 Creating Arrays
    • 2.1 Array with Initial Elements
    • 2.2 Modifying Elements
    • 2.3 Adding New Elements
    • 2.4 Array Length
    • 2.5 Displaying the Whole Array
    • 2.6 Mixed Types
  • 3 Get Last Elements with “at”
  • 4 Methods pop/push, shift/unshift
    • 4.1 Queue (FIFO - First In First Out)
    • 4.2 Stack (LIFO - Last In First Out)
    • 4.3 pop
    • 4.4 push
    • 4.5 shift
    • 4.6 unshift
    • 4.7 Multiple Elements
  • 5 Performance
  • 6 Loops
    • 6.1 for Loop
    • 6.2 for…of Loop
    • 6.3 for…in Loop (Not Recommended)
  • 7 Array Length
    • 7.1 Clearing an Array
  • 8 new Array()
  • 9 Multidimensional Arrays
  • 10 toString
  • 11 Don’t Compare Arrays with ==
    • 11.1 Comparison with Primitives
  • 12 Common Array Methods
    • 12.1 splice
    • 12.2 slice
    • 12.3 concat
    • 12.4 indexOf / lastIndexOf / includes
    • 12.5 find and findIndex
    • 12.6 filter
    • 12.7 map
    • 12.8 sort
    • 12.9 reverse
    • 12.10 split and join
    • 12.11 reduce
  • 13 Examples
    • 13.1 Example 1: Basic Array Operations
    • 13.2 Example 2: Iterating Over Arrays
    • 13.3 Example 3: Array Methods
    • 13.4 Example 4: Finding Elements
    • 13.5 Example 5: Sorting
  • 14 Summary
  • Edit this page
  • View source
  • Report an issue
  1. JavaScript Basics
  2. JavaScript: Arrays

JavaScript: Arrays

JavaScript Arrays

javascript
arrays
data-structures
JavaScript Arrays - Creating, Manipulating, and Iterating Over Arrays
Author

Pedro GeoGIS

Published

Monday, January 13, 2025

Modified

Monday, October 13, 2025

1 Overview

📘 Arrays

Arrays are special data structures used to store ordered collections of values. Unlike objects which store keyed collections, arrays maintain the order of elements and provide methods to manage that order. Arrays can hold values of any type and are zero-indexed (the first element is at index 0). They are essential for working with lists of data like users, products, or any sequential information.


2 Creating Arrays

There are two syntaxes for creating an empty array:

let arr = new Array();
let arr = [];

Recommendation: Use the square brackets [] syntax as it’s shorter and more common.


2.1 Array with Initial Elements

let fruits = ["Apple", "Orange", "Plum"];

Array elements are numbered, starting with zero. We can get an element by its number in square brackets:

let fruits = ["Apple", "Orange", "Plum"];

alert(fruits[0]);  // Apple
alert(fruits[1]);  // Orange
alert(fruits[2]);  // Plum

2.2 Modifying Elements

fruits[2] = 'Pear';  // now ["Apple", "Orange", "Pear"]

2.3 Adding New Elements

fruits[3] = 'Lemon';  // now ["Apple", "Orange", "Pear", "Lemon"]

2.4 Array Length

The total count of elements in the array is its length:

let fruits = ["Apple", "Orange", "Plum"];
alert(fruits.length);  // 3

2.5 Displaying the Whole Array

let fruits = ["Apple", "Orange", "Plum"];
alert(fruits);  // Apple,Orange,Plum

2.6 Mixed Types

An array can store elements of any type:

let arr = [
  'Apple',
  { name: 'John' },
  true,
  function() { alert('hello'); }
];

// get the object at index 1 and show its name
alert(arr[1].name);  // John

// get the function at index 3 and run it
arr[3]();  // hello

3 Get Last Elements with “at”

To get the last element, we can use negative indices with the at() method:

let fruits = ["Apple", "Orange", "Plum"];

alert(fruits.at(-1));  // Plum (last element)
alert(fruits.at(-2));  // Orange (second to last)

This is the same as:

alert(fruits[fruits.length - 1]);  // Plum

4 Methods pop/push, shift/unshift

Arrays in JavaScript can work both as a queue and as a stack.

4.1 Queue (FIFO - First In First Out)

  • push – appends an element to the end
  • shift – gets an element from the beginning

4.2 Stack (LIFO - Last In First Out)

  • push – adds an element to the end
  • pop – takes an element from the end

4.3 pop

Extracts the last element of the array and returns it:

let fruits = ["Apple", "Orange", "Pear"];

alert(fruits.pop());  // remove "Pear" and alert it
alert(fruits);        // Apple, Orange

Both fruits.pop() and fruits.at(-1) return the last element, but fruits.pop() also modifies the array by removing it.


4.4 push

Appends the element to the end of the array:

let fruits = ["Apple", "Orange"];

fruits.push("Pear");

alert(fruits);  // Apple, Orange, Pear

The call fruits.push(...) is equal to fruits[fruits.length] = ....


4.5 shift

Extracts the first element of the array and returns it:

let fruits = ["Apple", "Orange", "Pear"];

alert(fruits.shift());  // remove Apple and alert it
alert(fruits);          // Orange, Pear

4.6 unshift

Adds the element to the beginning of the array:

let fruits = ["Orange", "Pear"];

fruits.unshift('Apple');

alert(fruits);  // Apple, Orange, Pear

4.7 Multiple Elements

Methods push and unshift can add multiple elements at once:

let fruits = ["Apple"];

fruits.push("Orange", "Peach");
fruits.unshift("Pineapple", "Lemon");

alert(fruits);  // Pineapple, Lemon, Apple, Orange, Peach

5 Performance

Methods push/pop are fast, while shift/unshift are slow.

Why?

  • push/pop work with the end of the array (no need to renumber other elements)
  • shift/unshift work with the beginning (all elements need to be renumbered)

The more elements in the array, the more time to move them, more in-memory operations.


6 Loops

6.1 for Loop

The most common way to loop over array elements:

let fruits = ["Apple", "Orange", "Plum"];

for (let i = 0; i < fruits.length; i++) {
  alert(fruits[i]);
}

6.2 for…of Loop

A special form of loop for iterating over array values:

let fruits = ["Apple", "Orange", "Plum"];

for (let fruit of fruits) {
  alert(fruit);
}

The for...of doesn’t give access to the index, just the value. But that’s enough for most cases.


6.3 for…in Loop (Not Recommended)

Technically, because arrays are objects, it’s possible to use for...in:

let arr = ["Apple", "Orange", "Pear"];

for (let key in arr) {
  alert(arr[key]);  // Apple, Orange, Pear
}

But this is a bad idea because: 1. for...in iterates over all properties, not only numeric ones 2. for...in is optimized for generic objects, not arrays (10-100 times slower)

Use for...of or regular for loop for arrays.


7 Array Length

The length property automatically updates when we modify the array. It’s not the count of values, but the greatest numeric index plus one:

let fruits = [];
fruits[123] = "Apple";

alert(fruits.length);  // 124

7.1 Clearing an Array

The simplest way to clear an array is:

arr.length = 0;

8 new Array()

There’s one more syntax to create an array:

let arr = new Array("Apple", "Pear", "etc");

It’s rarely used because square brackets [] are shorter.

Gotcha: If new Array is called with a single numeric argument, it creates an array without items, but with the given length:

let arr = new Array(2);  // will it create an array of [2]?

alert(arr[0]);     // undefined! no elements.
alert(arr.length); // length 2

9 Multidimensional Arrays

Arrays can have items that are also arrays. We can use it for multidimensional arrays:

let matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

alert(matrix[1][1]);  // 5, the central element

10 toString

Arrays have their own implementation of toString method that returns a comma-separated list of elements:

let arr = [1, 2, 3];

alert(arr);           // 1,2,3
alert(String(arr));   // 1,2,3
alert(arr.toString()); // 1,2,3

11 Don’t Compare Arrays with ==

Arrays in JavaScript shouldn’t be compared with operator ==.

This operator has no special treatment for arrays, it works with them as with any objects.

alert([] == []);   // false
alert([0] == [0]); // false

Arrays are objects, so they are compared by reference. Two independent arrays are never equal.


11.1 Comparison with Primitives

alert(0 == []);    // true
alert('0' == []);  // false

When an array is compared with a primitive, it’s converted to a primitive for comparison.

Recommendation: Don’t use == with arrays. Instead, compare them item-by-item, or use iteration methods.


12 Common Array Methods

12.1 splice

The splice() method can insert, remove and replace elements:

arr.splice(start, deleteCount, elem1, ..., elemN)

Examples:

let arr = ["I", "study", "JavaScript"];

// remove 1 element from index 1
arr.splice(1, 1);
alert(arr);  // ["I", "JavaScript"]
let arr = ["I", "study", "JavaScript", "right", "now"];

// remove 3 first elements and replace them with another
arr.splice(0, 3, "Let's", "dance");
alert(arr);  // ["Let's", "dance", "right", "now"]

12.2 slice

Returns a new array copying all items from index start to end (not including end):

arr.slice([start], [end])
let arr = ["t", "e", "s", "t"];

alert(arr.slice(1, 3));  // e,s (copy from 1 to 3)
alert(arr.slice(-2));    // s,t (copy from -2 till the end)

12.3 concat

Creates a new array that includes values from other arrays and additional items:

arr.concat(arg1, arg2...)
let arr = [1, 2];

alert(arr.concat([3, 4]));        // 1,2,3,4
alert(arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6
alert(arr.concat([3, 4], 5, 6));   // 1,2,3,4,5,6

12.4 indexOf / lastIndexOf / includes

  • arr.indexOf(item, from) – looks for item starting from index from, returns the index or -1
  • arr.lastIndexOf(item, from) – same, but looks from right to left
  • arr.includes(item, from) – looks for item starting from index from, returns true if found
let arr = [1, 0, false];

alert(arr.indexOf(0));     // 1
alert(arr.indexOf(false)); // 2
alert(arr.indexOf(null));  // -1

alert(arr.includes(1));    // true

12.5 find and findIndex

Used to find objects with specific conditions:

let result = arr.find(function(item, index, array) {
  // should return true if the item is what we are looking for
});
let users = [
  {id: 1, name: "John"},
  {id: 2, name: "Pete"},
  {id: 3, name: "Mary"}
];

let user = users.find(item => item.id == 1);

alert(user.name);  // John

12.6 filter

Returns an array of all matching elements:

let results = arr.filter(function(item, index, array) {
  // should return true if the item passes the filter
});
let users = [
  {id: 1, name: "John"},
  {id: 2, name: "Pete"},
  {id: 3, name: "Mary"}
];

let someUsers = users.filter(item => item.id < 3);

alert(someUsers.length);  // 2

12.7 map

Calls the function for each element and returns the array of results:

let result = arr.map(function(item, index, array) {
  // returns the new value instead of item
});
let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length);
alert(lengths);  // 5,7,6

12.8 sort

Sorts the array in place, changing element order:

let arr = [1, 2, 15];

arr.sort();
alert(arr);  // 1, 15, 2

Note: Items are sorted as strings by default.

To sort numbers correctly:

let arr = [1, 2, 15];

arr.sort((a, b) => a - b);
alert(arr);  // 1, 2, 15

12.9 reverse

Reverses the order of elements in the array:

let arr = [1, 2, 3, 4, 5];
arr.reverse();

alert(arr);  // 5,4,3,2,1

12.10 split and join

str.split(delim) splits the string into an array by the given delimiter:

let names = 'Bilbo, Gandalf, Nazgul';
let arr = names.split(', ');

for (let name of arr) {
  alert(`A message to ${name}.`);
}

arr.join(glue) does the reverse – creates a string from array items glued by glue:

let arr = ['Bilbo', 'Gandalf', 'Nazgul'];
let str = arr.join(';');

alert(str);  // Bilbo;Gandalf;Nazgul

12.11 reduce

Used to calculate a single value based on the array:

let value = arr.reduce(function(accumulator, item, index, array) {
  // ...
}, [initial]);
let arr = [1, 2, 3, 4, 5];

let result = arr.reduce((sum, current) => sum + current, 0);

alert(result);  // 15

13 Examples

13.1 Example 1: Basic Array Operations

let fruits = ["Apple", "Banana", "Orange"];

console.log(fruits[0]);      // Apple
console.log(fruits.length);  // 3

fruits.push("Mango");
console.log(fruits);  // ["Apple", "Banana", "Orange", "Mango"]

fruits.pop();
console.log(fruits);  // ["Apple", "Banana", "Orange"]

13.2 Example 2: Iterating Over Arrays

let numbers = [1, 2, 3, 4, 5];

// for loop
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

// for...of loop
for (let num of numbers) {
  console.log(num);
}

13.3 Example 3: Array Methods

let numbers = [1, 2, 3, 4, 5];

// map - double each number
let doubled = numbers.map(n => n * 2);
console.log(doubled);  // [2, 4, 6, 8, 10]

// filter - get even numbers
let evens = numbers.filter(n => n % 2 === 0);
console.log(evens);  // [2, 4]

// reduce - sum all numbers
let sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum);  // 15

13.4 Example 4: Finding Elements

let users = [
  { id: 1, name: "John", age: 25 },
  { id: 2, name: "Jane", age: 30 },
  { id: 3, name: "Bob", age: 35 }
];

// find user with id 2
let user = users.find(u => u.id === 2);
console.log(user.name);  // Jane

// filter users over 25
let adults = users.filter(u => u.age > 25);
console.log(adults.length);  // 2

13.5 Example 5: Sorting

let numbers = [3, 1, 4, 1, 5, 9, 2, 6];

// sort ascending
numbers.sort((a, b) => a - b);
console.log(numbers);  // [1, 1, 2, 3, 4, 5, 6, 9]

// sort descending
numbers.sort((a, b) => b - a);
console.log(numbers);  // [9, 6, 5, 4, 3, 2, 1, 1]

14 Summary

  • Arrays are ordered collections of values
  • Create arrays with [] or new Array()
  • Access elements by index: arr[0], arr[1], etc.
  • Arrays are zero-indexed (first element is at index 0)
  • Use length property to get the number of elements
  • push/pop work with the end of the array
  • shift/unshift work with the beginning of the array
  • Use for...of to iterate over array values
  • Use map() to transform array elements
  • Use filter() to select elements that match a condition
  • Use find() to find a single element
  • Use reduce() to calculate a single value from the array
  • Use sort() to sort array elements
  • Use splice() to insert, remove, or replace elements
  • Use slice() to copy a portion of an array
  • Use concat() to merge arrays
  • Don’t compare arrays with == operator
Back to top
JavaScript: Functions
JavaScript: Objects

License: CC0 1.0 Universal

Per aspera, ad astra

  • Edit this page
  • View source
  • Report an issue