본문으로 건너뛰기
Previous
Next
JavaScript Arrays and Objects — Complete Guide

JavaScript Arrays and Objects — Complete Guide

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);
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

  1. Array: add/remove, search, map/filter/reduce, sort carefully for numbers.
  2. Object: literals, Object.keys/values/entries.
  3. Destructuring: arrays and objects.
  4. Spread/rest: copy, merge, gather rest.
  5. Higher-order: map, filter, reduce for data transformations.

Best practices

  1. Prefer immutable-style patterns when reasonable.
  2. Chain methods for readability.
  3. Use spread for shallow copies.
  4. Use destructuring to reduce noise.

Next steps



자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. JavaScript arrays and objects: map, filter, reduce, sorting, Object.keys/entries, destructuring, spread/rest—patterns fo… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. JavaScript 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

JavaScript, Array, Object, map, filter, reduce, Destructuring 등으로 검색하시면 이 글이 도움이 됩니다.