How to use an Array object in JavaScript

12 Answers

0 votes
// ==================================================
// Title: Creating and Accessing an Array
// ==================================================
//
// Arrays store ordered collections of values.
// Elements are accessed using zero-based indexes.
//

// JavaScript Array Best Practices:
//
// Use const for array references when possible.
// Prefer array methods such as map, filter,
// find, and reduce over manual loops when they
// improve readability.
// Avoid mutating arrays unnecessarily.
// Use descriptive variable names.
// Prefer for...of when iterating over values.
// Use spread syntax (...) when creating copies.
// Store related data in objects rather than using
// multiple parallel arrays.
// Keep array transformations predictable by
// returning new arrays whenever practical.

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

// Access elements by index.
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

// Array length tells us how many elements exist.
console.log("Total fruits:", fruits.length);


/*
run:

Apple
Banana
Orange
Total fruits: 3

*/

 



answered Oct 10 by avibootz
edited Oct 10 by avibootz
0 votes
// ==================================================
// Title: Adding and Removing Elements
// ==================================================
//
// push() adds to the end.
// pop() removes from the end.
// unshift() adds to the beginning.
// shift() removes from the beginning.
//

const colors = ["Red", "Green"];

colors.push("Blue");
console.log(colors);

colors.unshift("Yellow");
console.log(colors);

colors.pop();
console.log(colors);

colors.shift();
console.log(colors);


/*
run:

[ 'Red', 'Green', 'Blue' ]
[ 'Yellow', 'Red', 'Green', 'Blue' ]
[ 'Yellow', 'Red', 'Green' ]
[ 'Red', 'Green' ]

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Iterating Through an Array
// ==================================================
//
// The for...of loop is a clean and readable way
// to iterate over array values.
//

const cities = [
    "London",
    "Paris",
    "Tokyo"
];

for (const city of cities) {
    console.log(city);
}


/*
run:

London
Paris
Tokyo

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Using forEach()
// ==================================================
//
// forEach() executes a callback for each element.
//
// It is useful when you need to perform actions
// such as logging or updating the UI.
//

const numbers = [10, 20, 30];

numbers.forEach((value, index) => {
    console.log(
        `Index: ${index}, Value: ${value}`
    );
});


/*
run:

Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Using map()
// ==================================================
//
// map() transforms each element and returns
// a new array.
//
// The original array is not modified.
//

// Creating a New Array with map()

const prices = [10, 20, 30];

const discountedPrices = prices.map(
    price => price * 0.9
);

console.log(prices);
console.log(discountedPrices);



/*
run:

Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Using filter()
// ==================================================
//
// filter() creates a new array containing only
// elements that satisfy a condition.
//

// Filtering Array Elements

const scores = [45, 82, 91, 29, 67];

const passingScores = scores.filter(
    score => score >= 60
);

console.log("All scores:", scores);
console.log(
    "Passing scores:",
    passingScores
);


/*
run:

All scores: [ 45, 82, 91, 29, 67 ]
Passing scores: [ 82, 91, 67 ]

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Using find()
// ==================================================
//
// find() returns the first matching element.
//
// If no match is found, it returns undefined.
//

// Finding an Element

const users = [
    { id: 1, name: "Cora" },
    { id: 2, name: "Nova" },
    { id: 3, name: "Kyron" }
];

const user = users.find(
    user => user.id === 2
);

console.log(user);


/*
run:

{ id: 2, name: 'Nova' }

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Using reduce()
// ==================================================
//
// reduce() combines array elements into
// a single value.
//
// Common uses include sums, averages,
// and grouped statistics.
//

// Reducing an Array

const sales = [120, 180, 250, 300];

const totalSales = sales.reduce(
    (total, current) => total + current,
    0
);

console.log("Total sales:", totalSales);



/*
run:

Total sales: 850

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Sorting an Array
// ==================================================
//
// Provide a comparison function when sorting
// numbers to avoid unexpected results.
//

const numbers = [50, 2, 100, 25];

const sortedNumbers = [...numbers].sort(
    (a, b) => a - b
);

console.log("Original:", numbers);
console.log("Sorted:", sortedNumbers);



/*
run:

Original: [ 50, 2, 100, 25 ]
Sorted: [ 2, 25, 50, 100 ]

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Arrays of Objects
// ==================================================
//
// Arrays often contain objects that represent
// real-world entities.
//

// Working with Arrays of Objects

const products = [
    {
        id: 1,
        name: "Laptop",
        price: 1200
    },
    {
        id: 2,
        name: "Mouse",
        price: 25
    },
    {
        id: 3,
        name: "Keyboard",
        price: 80
    }
];

const expensiveProducts = products.filter(
    product => product.price > 100
);

expensiveProducts.forEach(product => {
    console.log(
        `${product.name}: $${product.price}`
    );
});


/*
run:

Original: [ 50, 2, 100, 25 ]
Sorted: [ 2, 25, 50, 100 ]

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Combining Array Methods
// ==================================================
//
// Modern JavaScript frequently chains
// array operations together.
//
// This approach is expressive and easy
// to maintain.
//

const orders = [
    { amount: 100 },
    { amount: 250 },
    { amount: 80 },
    { amount: 300 }
];

const result = orders
    .filter(order => order.amount >= 100)
    .map(order => order.amount)
    .reduce(
        (total, amount) => total + amount,
        0
    );

console.log("Total:", result);


/*
run:

Total: 650

*/

 



answered Oct 10 by avibootz
0 votes
// ==================================================
// Title: Common Array Methods
// ==================================================

// Useful Array Object Methods

const values = [1, 2, 3, 4, 5];

console.log(values.includes(3));

console.log(
    values.indexOf(4)
);

console.log(
    values.slice(1, 4)
);

console.log(
    values.join(", ")
);

console.log(
    Array.isArray(values)
);


/*
run:

true
3
[ 2, 3, 4 ]
1, 2, 3, 4, 5
true

*/

 



answered Oct 10 by avibootz
...