JavaScript Arrays and Objects — Complete Guide
이 글의 핵심
JavaScript arrays and objects: map, filter, reduce, sorting, Object.keys/entries, destructuring, spread/rest—patterns for everyday JS code.
Introduction
Arrays and objects are the data structures you will use most often in JavaScript.
1. Arrays
Creating and indexing
let fruits = ["apple", "banana", "cherry"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "hello", true, null, { name: "Alice" }];
let empty1 = [];
let empty2 = new Array();
let arr = new Array(5);
console.log(arr.length);
console.log(fruits[0]);
console.log(fruits[fruits.length - 1]);
fruits[1] = "grape";
Add / remove
let arr = [1, 2, 3];
arr.push(4);
let last = arr.pop();
arr.unshift(0);
let first = arr.shift();
arr.splice(1, 1);
arr.splice(1, 0, 2);
arr.splice(1, 1, 10, 20);
Search
let numbers = [1, 2, 3, 4, 5, 3];
console.log(numbers.indexOf(3));
console.log(numbers.lastIndexOf(3));
console.log(numbers.includes(3));
let found = numbers.find(x => x > 3);
let index = numbers.findIndex(x => x > 3);
console.log(numbers.some(x => x > 4));
console.log(numbers.every(x => x > 0));
Transform: map, filter, reduce
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(x => x * 2);
let evens = numbers.filter(x => x % 2 === 0);
let sum = numbers.reduce((acc, x) => acc + x, 0);
let words = ["apple", "banana", "cherry"];
let wordLengths = words.reduce((acc, word) => {
acc[word] = word.length;
return acc;
}, {});
let nested = [[1, 2], [3, 4], [5]];
let flattened = nested.reduce((acc, a) => acc.concat(a), []);
Chaining:
// 변수 선언 및 초기화
let result = numbers
.filter(x => x > 2)
.map(x => x * 2)
.reduce((a, b) => a + b, 0);
Mutating vs non-mutating:
- Mutates:
push,pop,shift,unshift,splice,sort,reverse - Does not mutate:
map,filter,reduce,slice,concat
Sorting
let numbers = [3, 1, 4, 1, 5, 9, 2];
numbers.sort();
numbers.sort((a, b) => b - a);
let words = ["banana", "apple", "cherry"];
words.sort();
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Carol", age: 20 }
];
users.sort((a, b) => a.age - b.age);
numbers.reverse();
More helpers
let arr = [1, 2, 3, 4, 5];
let sub = arr.slice(1, 4);
let combined = [1, 2].concat([3, 4]);
let joined = arr.join(", ");
let nested = [1, [2, 3], [4, [5, 6]]];
nested.flat();
nested.flat(2);
nested.flat(Infinity);
let words = ["hello world", "foo bar"];
words.flatMap(word => word.split(" "));
2. Objects
Literals and property access
let person = {
name: "Alice",
age: 25,
city: "Seoul"
};
console.log(person.name);
console.log(person[age]);
let key = "city";
console.log(person[key]);
person.job = "developer";
person.age = 26;
delete person.city;
Methods
let person = {
name: "Alice",
age: 25,
greet: function() {
console.log(`Hello, ${this.name}.`);
},
introduce() {
console.log(`${this.age} years old — ${this.name}.`);
}
};
Static Object methods
let person = { name: "Alice", age: 25, city: "Seoul" };
Object.keys(person);
Object.values(person);
Object.entries(person);
for (let [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}
let defaults = { theme: "dark", lang: "ko" };
let userSettings = { lang: "en" };
let settings = Object.assign({}, defaults, userSettings);
let frozen = Object.freeze({ x: 10 });
let sealed = Object.seal({ x: 10 });
3. Destructuring
Arrays
let arr = [1, 2, 3, 4, 5];
let [a, b] = arr;
let [first, ...rest] = arr;
let [x, , z] = arr;
let [m, n] = [10, 20];
[m, n] = [n, m];
Objects
let person = { name: "Alice", age: 25, city: "Seoul" };
let { name, age } = person;
let { name: userName, age: userAge } = person;
let { name, age, job = "n/a" } = person;
let { name, ...rest } = person;
let user = {
id: 1,
profile: { name: "Alice", age: 25 }
};
let { profile: { name, age } } = user;
Function parameters
function printUser({ name, age, city = "Seoul" }) {
console.log(`${name} (${age}, ${city})`);
}
function getMinMax([first, ...rest]) {
return {
min: Math.min(first, ...rest),
max: Math.max(first, ...rest)
};
}
4. Spread and rest
Spread
let combined = [...[1, 2, 3], ...[4, 5, 6]];
let original = [1, 2, 3];
let copy = [...original];
function add(a, b, c) {
return a + b + c;
}
add(...[1, 2, 3]);
let merged = { ...{ a: 1 }, ...{ b: 2 } };
let person = { name: "Alice", age: 25 };
let personCopy = { ...person };
let defaults = { theme: "dark", lang: "ko" };
let userSettings = { ...defaults, lang: "en" };
Rest
function sum(...numbers) {
return numbers.reduce((acc, x) => acc + x, 0);
}
let [first, second, ...rest] = [1, 2, 3, 4, 5];
let { name, ...otherInfo } = { name: "Alice", age: 25, city: "Seoul" };
5. Advanced array usage
forEach vs map
let numbers = [1, 2, 3];
numbers.forEach(x => console.log(x * 2));
let doubled = numbers.map(x => x * 2);
reduce patterns
let words = ["apple", "banana", "apple", "cherry", "banana", "apple"];
let frequency = words.reduce((acc, word) => {
acc[word] = (acc[word] || 0) + 1;
return acc;
}, {});
let users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
let userMap = users.reduce((acc, user) => {
acc[user.id] = user;
return acc;
}, {});
let students = [
{ name: "Alice", grade: "A" },
{ name: "Bob", grade: "B" },
{ name: "Carol", grade: "A" }
];
let grouped = students.reduce((acc, s) => {
if (!acc[s.grade]) acc[s.grade] = [];
acc[s.grade].push(s.name);
return acc;
}, {});
Chaining example
let users = [
{ name: "Alice", age: 25, active: true },
{ name: "Bob", age: 17, active: false },
{ name: "Carol", age: 30, active: true }
];
let activeAdultNames = users
.filter(u => u.active && u.age >= 18)
.map(u => u.name)
.sort();
6. Practical examples
Array utilities
function unique(arr) {
return [...new Set(arr)];
}
function chunk(arr, size) {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
function difference(arr1, arr2) {
return arr1.filter(x => !arr2.includes(x));
}
function intersection(arr1, arr2) {
return arr1.filter(x => arr2.includes(x));
}
Object helpers
function deepClone(obj) {
if (obj === null || typeof obj !== "object") return obj;
if (Array.isArray(obj)) return obj.map(deepClone);
const cloned = {};
for (let key in obj) {
cloned[key] = deepClone(obj[key]);
}
return cloned;
}
function filterObject(obj, predicate) {
return Object.keys(obj)
.filter(key => predicate(obj[key], key))
.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
}
CSV helpers
function parseCSV(csv) {
const lines = csv.trim().split("\n");
const headers = lines[0].split(",");
return lines.slice(1).map(line => {
const values = line.split(",");
return headers.reduce((obj, header, i) => {
obj[header] = values[i];
return obj;
}, {});
});
}
function toCSV(arr) {
if (arr.length === 0) return "";
const headers = Object.keys(arr[0]);
const headerRow = headers.join(",");
const dataRows = arr.map(obj =>
headers.map(h => obj[h]).join(",")
);
return [headerRow, ...dataRows].join("\n");
}
7. Common mistakes
Copying arrays
let arr1 = [1, 2, 3];
let arr2 = arr1;
arr2[0] = 100;
let arr3 = [...arr1];
let nested = [[1, 2], [3, 4]];
let copy = [...nested];
copy[0][0] = 999;
let deepCopy = JSON.parse(JSON.stringify(nested));
Numeric sort
let numbers = [1, 10, 2, 20, 3];
numbers.sort();
numbers.sort((a, b) => a - b);
Object identity
let obj1 = { a: 1 };
let obj2 = { a: 1 };
console.log(obj1 === obj2); // false
function deepEqual(obj1, obj2) {
if (obj1 === obj2) return true;
if (typeof obj1 !== "object" || typeof obj2 !== "object" ||
obj1 === null || obj2 === null) return false;
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
if (keys1.length !== keys2.length) return false;
for (let key of keys1) {
if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) return false;
}
return true;
}
8. Exercises
Flatten
function flatten(arr) {
return arr.reduce((acc, item) =>
acc.concat(Array.isArray(item) ? flatten(item) : item), []);
}
groupBy
function groupBy(arr, key) {
return arr.reduce((acc, obj) => {
const g = obj[key];
if (!acc[g]) acc[g] = [];
acc[g].push(obj);
return acc;
}, {});
}
Rotate
function rotateArray(arr, k) {
k = k % arr.length;
return [...arr.slice(-k), ...arr.slice(0, -k)];
}
Summary
Key points
- Array: add/remove, search,
map/filter/reduce, sort carefully for numbers. - Object: literals,
Object.keys/values/entries. - Destructuring: arrays and objects.
- Spread/rest: copy, merge, gather rest.
- Higher-order:
map,filter,reducefor data transformations.
Best practices
- Prefer immutable-style patterns when reasonable.
- Chain methods for readability.
- Use spread for shallow copies.
- Use destructuring to reduce noise.
Next steps
Related posts
Frequently Asked Questions (FAQ)
Q. When would I use this in practice?
A. JavaScript arrays and objects: map, filter, reduce, sorting, Object.keys/entries, destructuring, spread/rest—patterns fo…
Q. What should I read before this?
A. Follow the previous article or related articles links at the bottom of each post to learn in sequence. See the JavaScript series index for the full picture.
Q. Where can I study this more deeply?
A. Check cppreference and the relevant library’s official documentation. The reference links at the end of the article are also worth using.
Related Articles (Internal Links)
Other articles related to this topic.
- JavaScript 함수 | 함수 선언, 화살표 함수, 콜백, 클로저 완벽 정리
- JavaScript 배열과 객체 | Array, Object 메서드 완벽 정리
- Get Started with JavaScript
Keywords Covered in This Article (Related Search Terms)
This article covers JavaScript, Array, Object, map, filter, reduce, Destructuring.