Array Fundamentals
By Syncfusion®, Inc. · Last updated
Creating arrays and reading items by index, push, pop, unshift and shift, slice versus splice, copying with spread, changing a list without changing the original with map, filter, with and toSpliced, combining with concat, and flattening with flat and flatMap.
What Is an Array?
Array = an ordered list of values, kept under one name.
- Written in square brackets:
["Pen", "Notebook", "Bag"]. - Each item has a position called an index, starting at
0. lengthtells you how many items there are.
Simple lesson: an array is a numbered row of boxes. Box 0 is the first one.
A Real-World Example
A customer adds a pen, a notebook and a bag to the cart.
The shop keeps them in one array, cart, instead of three variables.
Adding an item is cart.push(...). Removing one makes a new list without it.
"Pen" 0
"Notebook" 1
"Bag" 2
"Mug" 3
cart.push("Mug"): length 3 → 4
Indexes start at 0. push() adds a box at the end.
What You Will Learn
- How to create an array and read its items.
- How to add and remove items at the ends.
slice()andsplice(), and copying arrays.- Changing a list without changing the original.
- Combining and flattening arrays.
Array basics
A cart with three items
const cart = ["Pen", "Notebook", "Bag"];
console.log(cart);
console.log(cart.length);
console.log(cart[0], cart[2]);
Expected output:
[
"Pen",
"Notebook",
"Bag"
]
3
Pen Bag
Creating arrays
[]makes an empty array.["a", "b"]makes one with items.Array.from({ length: 3 }, (_, i) => i + 1)builds[1, 2, 3]from a function.typeofsays"object"for arrays, so check withArray.isArray(value).
Two ways to start an array
const empty = [];
const prices = [20, 60, 799];
console.log(empty.length, prices.length);
empty.push("first");
console.log(empty.join(", "));
console.log(Array.from({ length: 3 }, (_, i) => i + 1).join(", "));
console.log(Array.isArray(prices), typeof prices);
Expected output:
0 3
first
1, 2, 3
true object
Reading elements
cart[0]is the first item.cart[cart.length - 1]is the last.cart.at(-1)also gives the last item.- A missing index gives
undefined, not an error.
Reading the first, the last and a missing element
const cart = ["Pen", "Notebook", "Bag"];
console.log(cart[0]);
console.log(cart.at(-1));
console.log(cart[5]);
Expected output:
Pen
Bag
undefined
Adding and removing items
| Method | Does | End |
|---|---|---|
push(x) | Adds | Back |
pop() | Removes and returns | Back |
unshift(x) | Adds | Front |
shift() | Removes and returns | Front |
These four change the array itself.
push, pop, unshift and shift on a queue of orders
const queue = ["#101", "#102"];
console.log(queue.push("#103"));
console.log(queue);
console.log(queue.shift());
queue.unshift("#100");
console.log(queue.pop());
console.log(queue);
Expected output:
3
[
"#101",
"#102",
"#103"
]
#101
#103
[
"#100",
"#102"
]
push() returns the new length, not the array.
Array modification
slice()
slice(start, end) copies a part. The end index is not included. The original stays the same.
slice() copies a section and leaves the original alone
const items = ["Pen", "Notebook", "Bag", "Mug"];
const middle = items.slice(1, 3);
console.log(middle.join(", "));
console.log(items.join(", "));
Expected output:
Notebook, Bag
Pen, Notebook, Bag, Mug
splice()
splice(start, deleteCount, ...newItems) removes, inserts or replaces in place. It changes the original.
splice() removes, inserts and replaces in place
const items = ["Pen", "Notebook", "Bag", "Mug"];
const removed = items.splice(1, 1);
console.log(removed.join(", "), "|", items.join(", "));
items.splice(1, 0, "Ruler");
console.log(items.join(", "));
items.splice(2, 1, "Lunch box");
console.log(items.join(", "));
Expected output:
Notebook | Pen, Bag, Mug
Pen, Ruler, Bag, Mug
Pen, Ruler, Lunch box, Mug
slice = copy a piece. splice = cut the array itself.
Copying arrays
const b = a does not copy. Both names point to the same array. Use [...a] to copy.
Assignment shares the array, spread copies it
const cart = ["Pen"];
const shared = cart;
const copy = [...cart];
shared.push("Bag");
console.log(cart.join(", "));
console.log(copy.join(", "));
Expected output:
Pen, Bag
Pen
Updating arrays without changing the original
Pages and apps often keep the old list and build a new one. Two common ways:
Using map()
map() makes a new array with every item changed by your function.
Raising one price with map()
const products = [
{ name: "Pen", price: 20 },
{ name: "Bag", price: 799 },
];
const updated = products.map((p) => (p.name === "Pen" ? { ...p, price: 25 } : p));
console.log(updated.map((p) => `${p.name} ₹${p.price}`).join(", "));
console.log(products[0].price);
Expected output:
Pen ₹25, Bag ₹799
20
Using the spread operator
Copy the parts before and after, and put the new item in the middle.
Replacing one element with slice() and spread
const sizes = ["S", "M", "L"];
const i = 1;
const changed = [...sizes.slice(0, i), "XL", ...sizes.slice(i + 1)];
console.log(changed.join(", "));
console.log(sizes.with(i, "XL").join(", "));
console.log(sizes.join(", "));
Expected output:
S, XL, L
S, XL, L
S, M, L
with(index, value) does the same in one call: a copy with one item replaced.
Adding items without changing the original
Using the spread operator
A new array with an item added at each end
const cart = ["Pen", "Bag"];
const withMug = [...cart, "Mug"];
const withGift = ["Gift card", ...cart];
console.log(withMug.join(", "));
console.log(withGift.join(", "));
console.log(cart.join(", "));
Expected output:
Pen, Bag, Mug
Gift card, Pen, Bag
Pen, Bag
Using concat()
concat() returns a new array with the extra items at the end.
concat() adds items and returns a new array
const cart = ["Pen", "Bag"];
const bigger = cart.concat("Mug", "Ruler");
console.log(bigger.join(", "));
console.log(cart.length);
Expected output:
Pen, Bag, Mug, Ruler
2
Removing items without changing the original
Using filter()
filter() keeps the items for which your function returns true.
Removing one item, and removing every sold-out item
const products = [
{ name: "Pen", stock: 10 },
{ name: "Bag", stock: 0 },
{ name: "Mug", stock: 4 },
];
const withoutPen = products.filter((p) => p.name !== "Pen");
const inStock = products.filter((p) => p.stock > 0);
console.log(withoutPen.map((p) => p.name).join(", "));
console.log(inStock.map((p) => p.name).join(", "));
console.log(products.length);
Expected output:
Bag, Mug
Pen, Mug
3
Using slice() and the spread operator
To remove by position, join the part before and the part after.
Removing the element at index 2
const items = ["Pen", "Notebook", "Bag", "Mug"];
const i = 2;
const result = [...items.slice(0, i), ...items.slice(i + 1)];
console.log(result.join(", "));
console.log(items.toSpliced(i, 1).join(", "));
console.log(items.join(", "));
Expected output:
Pen, Notebook, Mug
Pen, Notebook, Mug
Pen, Notebook, Bag, Mug
toSpliced() works like splice(), but returns a changed copy and leaves the original alone.
Combining arrays
Using concat()
Merging three lists with concat()
const stationery = ["Pen", "Ruler"];
const bags = ["School bag"];
const bottles = ["Steel bottle"];
console.log(stationery.concat(bags, bottles).join(", "));
Expected output:
Pen, Ruler, School bag, Steel bottle
Using the spread operator
Spread lets you add single values between the lists, too.
Merging lists with spread, and adding a value between them
const morning = ["#101", "#102"];
const evening = ["#201"];
console.log([...morning, "--- lunch ---", ...evening].join(", "));
Expected output:
#101, #102, --- lunch ---, #201
Flattening arrays
Nested array = an array inside an array. Flatten = pull the inner items out into one list.
Using flat()
flat() removes one level. flat(2) removes two. flat(Infinity) removes all.
One level, two levels and every level
const nested = ["Pen", ["Bag", ["Mug", ["Cup"]]]];
console.log(JSON.stringify(nested.flat()));
console.log(JSON.stringify(nested.flat(2)));
console.log(JSON.stringify(nested.flat(Infinity)));
Expected output:
["Pen","Bag",["Mug",["Cup"]]]
["Pen","Bag","Mug",["Cup"]]
["Pen","Bag","Mug","Cup"]
Using flatMap()
flatMap() = map() then flat(). Great for "every item from every order".
Every item from every order, in one list
const orders = [
{ id: 1, items: ["Pen", "Ruler"] },
{ id: 2, items: [] },
{ id: 3, items: ["Bag"] },
];
console.log(orders.flatMap((o) => o.items).join(", "));
Expected output:
Pen, Ruler, Bag
Arrays on a Web Page
The cart is an array. Add uses spread to make a new array, remove uses filter(), and the page is redrawn from the array each time.
A cart page driven by one array
const shop = [
{ id: 1, name: "Notebook", price: 60 },
{ id: 2, name: "Steel bottle", price: 299 },
{ id: 3, name: "Pencil box", price: 120 },
];
let cart = [];
function draw() {
const cartList = document.querySelector("#cart");
cartList.innerHTML = "";
for (const item of cart) {
const li = document.createElement("li");
li.textContent = `${item.name} — ₹${item.price} `;
const remove = document.createElement("button");
remove.textContent = "Remove";
remove.className = "ghost";
remove.addEventListener("click", () => {
cart = cart.filter((c) => c !== item);
draw();
});
li.append(remove);
cartList.append(li);
}
let total = 0;
for (const item of cart) total += item.price;
document.querySelector("#total").textContent = `₹${total}`;
console.log("cart:", cart.map((c) => c.name).join(", ") || "(empty)");
}
for (const product of shop) {
const li = document.createElement("li");
const add = document.createElement("button");
add.textContent = `Add ${product.name}`;
add.addEventListener("click", () => {
cart = [...cart, product];
draw();
});
li.append(add);
document.querySelector("#shop").append(li);
}
document.querySelector("#clear").addEventListener("click", () => {
cart = [];
draw();
});
draw();
Add a few items, remove one, then press Empty cart. The Console prints the array after each change.
Easy way to remember: push, pop, shift, unshift and splice change the array. slice, concat, map, filter, flat and spread make a new one.
TL;DR
- Arrays are ordered lists. Indexes start at
0;at(-1)is the last item. push/popwork at the back,unshift/shiftat the front, and all change the array.slicecopies a piece;splicecuts the array itself.const b = ashares;[...a]copies.- Use spread,
concat,map,filterandflatto make new arrays safely.
Try this
In Copying arrays, change const copy = [...cart] to const copy = cart. Now both lines print Pen, Bag. Two names, one array.
Check Yourself
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
cart[cart.length] for the last item | The last index is the length | It is length - 1, or use at(-1) | undefined |
const copy = cart | That makes a copy | It shares the same array | Changing one changes both |
splice when you meant slice | Both copy | splice changes the original | Items vanish from the list |
const n = cart.push(x) then using n as the array | push returns the array | It returns the new length | n.map is not a function |
nested.flat() on deep lists | It flattens everything | It removes one level | Inner arrays remain |
Quick reference
| Syntax | Meaning |
|---|---|
[a, b, c] | create an array |
Array.from({ length: n }, fn) | create an array of n elements from a function |
array[i], array.at(-1) | read an element, or the last element |
array.length | the number of elements |
push(x) / pop() | add or remove at the end, changing the array |
unshift(x) / shift() | add or remove at the start, changing the array |
slice(start, end) | copy a section, without changing the array |
splice(start, count, ...items) | remove and insert in place, changing the array |
[...array] | a shallow copy |
array.map((x, i) => i === n ? value : x) | a copy with one element replaced |
array.with(i, value) | a copy with the element at i replaced |
[...array, x], array.concat(x) | a copy with an element added |
array.filter((x) => x !== value) | a copy without matching elements |
[...array.slice(0, i), ...array.slice(i + 1)] | a copy without the element at i |
[...first, ...second], first.concat(second) | a new array combining both |
array.flat(depth) | unpack nested arrays |
array.flatMap(fn) | map, then flatten one level |
Exercises
What to Remember
- An array is a numbered list, starting at 0.
- Know which methods change the array and which make a new one.
- Pages often redraw from an array after each change.
Next: Array Operations. Search, sort and summarise arrays with find, sort and reduce.