💻 Programming

Array

Array

A contiguous storage structure for elements of the same type. O(1) index access. A fundamental data structure.

📖 Detailed Explanation

An array is the most basic data structure that stores elements of the same data type in a contiguous block of memory. Each element can be accessed by an index starting from 0, and through memory address calculation, random access is possible in O(1) time complexity.

The key characteristic of an array is contiguous memory allocation. As a result, the CPU cache hit rate is high, delivering excellent performance in sequential access. On the other hand, because its size is fixed, insertion/deletion in the middle takes O(n) time, and if dynamic resizing is needed, a new array must be allocated, which is a drawback.

Arrays are divided into static arrays and dynamic arrays. In C/C++, int arr[10] is a static array whose size is determined at compile time, while Python's list and JavaScript's Array are dynamic arrays whose size is automatically adjusted at runtime. A dynamic array internally implements amortized O(1) insertion by typically doubling its capacity when it runs out of space.

In practice, arrays are the foundation of all programming. Storing database query results, list data in API responses, image pixel values, and even machine learning tensor operations are impossible without arrays. In AI/ML in particular, NumPy arrays enable numerical computation more than 100 times faster than pure Python through vectorized operations.

💻 Code Example

// 1. 배열 생성 방법
const arr1 = [1, 2, 3, 4, 5];              // 리터럴 방식 (권장)
const arr2 = new Array(5);                  // 길이 5인 빈 배열
const arr3 = Array.from({length: 5}, (_, i) => i * 2); // [0, 2, 4, 6, 8]
const arr4 = [...Array(5).keys()];          // [0, 1, 2, 3, 4]

// 2. 배열 조작 (CRUD)
const fruits = ['apple', 'banana', 'cherry'];

// 추가
fruits.push('date');           // 끝에 추가: ['apple', 'banana', 'cherry', 'date']
fruits.unshift('avocado');     // 앞에 추가: ['avocado', 'apple', ...]
fruits.splice(2, 0, 'blueberry'); // 인덱스 2에 삽입

// 삭제
fruits.pop();                  // 마지막 요소 제거
fruits.shift();                // 첫 요소 제거
fruits.splice(1, 1);           // 인덱스 1의 요소 1개 제거

// 수정
fruits[0] = 'apricot';         // 인덱스로 직접 수정

// 3. 배열 순회 (Iteration)
const numbers = [1, 2, 3, 4, 5];

// for...of (값 순회, 권장)
for (const num of numbers) {
    console.log(num);
}

// forEach (콜백 함수)
numbers.forEach((num, index) => {
    console.log(`인덱스 ${index}: ${num}`);
});

// map (새 배열 반환)
const doubled = numbers.map(n => n * 2);  // [2, 4, 6, 8, 10]

// filter (조건 필터링)
const evens = numbers.filter(n => n % 2 === 0);  // [2, 4]

// reduce (누적 계산)
const sum = numbers.reduce((acc, n) => acc + n, 0);  // 15

// 4. 실무 패턴: 배열 검색과 정렬
const users = [
    { id: 1, name: 'Alice', age: 25 },
    { id: 2, name: 'Bob', age: 30 },
    { id: 3, name: 'Charlie', age: 35 }
];

// 찾기
const bob = users.find(u => u.name === 'Bob');      // { id: 2, ... }
const index = users.findIndex(u => u.id === 3);     // 2
const hasAdult = users.some(u => u.age >= 18);      // true
const allAdults = users.every(u => u.age >= 18);    // true

// 정렬 (원본 배열 변경 주의!)
const sorted = [...users].sort((a, b) => a.age - b.age);  // 나이순
const desc = [...users].sort((a, b) => b.age - a.age);    // 내림차순

🗣️ Say It Like This in Practice

💬 In a Meeting
"This API response can contain up to 100,000 records, and loading the whole thing into memory as an array could cause problems. It would be better to apply pagination or process it in a streaming manner."
💬 In an Interview
"Array index access is O(1) while a linked list is O(n). However, insertion/deletion in the middle is O(n) for an array and O(1) for a linked list. Choose an array when reads are frequent, and a linked list when insertions/deletions are frequent. JavaScript's Array is internally hash map-based, so it also handles sparse arrays efficiently."
💬 In a code review
"Here you're iterating over the array with a for loop while deleting elements with splice, and the indices can get tangled. Please change it to create a new array with filter, or to delete while iterating in reverse order."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
sort() modifies the original array

JavaScript's sort(), reverse(), splice(), and similar methods modify the original array directly. If you need to preserve the original, create a copy with [...arr].sort() or arr.slice().sort() and sort that.

❌
Use length when checking for an empty array

if(arr) is true even for an empty array. To check for an empty array, always use if(arr.length === 0) or if(!arr.length). With arr?.length, you can safely check for null/undefined as well.

✅
Optimize performance by choosing the right method

Use for...of for simple iteration, map for transformation, filter for filtering, and reduce for cumulative calculation. If early termination is needed, using find or some lets you get the result without iterating over the entire array.

🔗 Related Terms

📚 Learn More