본문 바로가기

DEVELOPE/앱개발시작하기

[20240505] 앱개발 시작하기 #8 | 배열

순회

: 배열, 객체에 저장된 여러개의 값에 순서대로 하나씩 접근하는 것

배열 순회 / 객체 순
//1. 배열 순회
let arr = [1,2,3]

//1. 배열 인덱스
for(let i=0; i<arr.length; i++){
	console.log(arr[i]);
}

let arr2 = [4,5,6,7,8];
for(let i=0; i<arr2.length; i++){
	console.log(arr2[i]);
}

//2. for of 반복문 : 인덱스 직접적 사용 불가
for(let item of arr){
	console.log(item);
}

//3. 객체 순회
let person={
	name: "토순이",
    age: "25",
    hobby:"테니스", 
}

// 3.1 object.keys 사용
=> 객체에서 key 값들만 뽑아서 새로운 배열로 반환
let keys = Object.keys{person};
console.log(keys);

// 3.2 object.values
=. 객체에서 value 값만 뽑아서 새로운 배열로 변환
let values = Object.values{values};

// 3.3 for in
for(let key in person){
	const value = person[key];
}

  1. push: 배열의 끝에 하나 이상의 요소를 추가합니다.
  2. pop: 배열의 끝에서 요소를 제거하고 그 값을 반환합니다.
  3. shift: 배열의 시작에서 요소를 제거하고 그 값을 반환합니다. 제거된 요소 이후의 요소들은 한 칸씩 앞으로 이동합니다.
  4. unshift: 배열의 시작에 하나 이상의 요소를 추가합니다. 추가된 요소 이후의 요소들은 한 칸씩 뒤로 이동합니다.
  5. slice: 배열에서 일부분을 추출하여 새로운 배열을 만드는 데 사용됩니다.
  6. concat: 배열에 다른 배열이나 값들을 추가하여 새로운 배열을 만듭니다. 기존 배열을 변경하지 않고, 새로운 배열을 반환합니다.
let arr = [1, 2, 3];

// push: 배열의 끝에 요소 추가
arr.push(4);
// arr는 이제 [1, 2, 3, 4]입니다.

// pop: 배열의 끝에서 요소 제거
let poppedValue = arr.pop();
// poppedValue는 4, arr은 [1, 2, 3]입니다.

// shift: 배열의 시작에서 요소 제거
let shiftedValue = arr.shift();
// shiftedValue는 1, arr은 [2, 3]입니다.

// unshift: 배열의 시작에 요소 추가
arr.unshift(0);
// arr은 이제 [0, 2, 3]입니다.

// slice
const array = [1, 2, 3, 4, 5];

// 인덱스 1부터 3까지의 요소를 추출한 새로운 배열 생성
const newArray = array.slice(1, 4); // [2, 3, 4]

console.log(newArray); // [2, 3, 4]
console.log(array);    // [1, 2, 3, 4, 5] (원본 배열은 변경되지 않음)

// concat
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];

// 두 배열을 합쳐서 새로운 배열 생성
const newArray = array1.concat(array2);

console.log(newArray); // [1, 2, 3, 4, 5, 6]
console.log(array1);   // [1, 2, 3] (원본 배열은 변경되지 않음)
console.log(array2);   // [4, 5, 6] (원본 배열은 변경되지 않음)

5가지 요소 순회 및 탐색 메서드

  1. forEach: 배열의 각 요소에 대해 주어진 함수를 실행합니다. 일반적으로 반복문을 대신하여 사용됩니다.
  2. includes: 배열에 특정 요소가 포함되어 있는지를 확인합니다. 포함되어 있다면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
  3. indexOf: 배열에서 주어진 요소를 찾고, 해당 요소의 인덱스를 반환합니다. 요소가 없으면 -1을 반환합니다
  4. findIndex: 주어진 조건을 만족하는 배열의 첫 번째 요소의 인덱스를 반환합니다. 만족하는 요소가 없으면 -1을 반환합니다.
  5. find: 주어진 조건을 만족하는 배열의 첫 번째 요소를 반환합니다. 만족하는 요소가 없으면 undefined를 반환합니다.
// forEach
const array = [1, 2, 3, 4, 5];

array.forEach(item => {
  console.log(item);
});

// includes
console.log(array.includes(3)); // true
console.log(array.includes(6)); // false

// indexOf
console.log(array.indexOf(3)); // 2
console.log(array.indexOf(6)); // -1

// findIndex
const index = array.findIndex(item => item === 3);
console.log(index); // 2

// find
const result = array.find(item => item === 3);
console.log(result); // 3

변형

  1. filter(함수, 반복 가능한 객체):
    • filter()는 파이썬의 내장 함수 중 하나로, 주어진 함수(조건)를 만족하는 요소들로 이루어진 반복 가능한 객체(예: 리스트)를 반환합니다.
    • 두 개의 인자를 받습니다: 함수와 반복 가능한 객체입니다.
    • 함수에 의해 True 또는 False가 반환되는 요소들을 필터링하여 이터레이터로 반환합니다.
  2. map(함수, 반복 가능한 객체):
    • map()은 파이썬의 내장 함수로, 주어진 함수를 반복 가능한 객체(예: 리스트)의 각 요소에 적용하고 결과의 맵 객체(이터레이터)를 반환합니다.
    • 두 개의 인자를 받습니다: 함수와 반복 가능한 객체입니다.
    • 함수를 반복 가능한 객체의 각 요소에 적용하고 결과를 이터레이터로 반환합니다.
  3. sort() 메소드:
    • sort()는 파이썬 리스트에 사용할 수 있는 메소드로, 리스트의 요소를 제자리에서 정렬합니다.
    • 원본 리스트를 수정하며 새로운 리스트를 반환하지 않습니다.
    • 기본적으로 오름차순으로 정렬되지만, reverse=True를 지정하여 내림차순으로 정렬할 수 있습니다.
  4. sorted(반복 가능한 객체, key=None, reverse=False):
    • sorted()는 파이썬의 내장 함수로, 반복 가능한 객체의 항목들로부터 새로운 정렬된 리스트를 반환합니다.
    • 원본 반복 가능한 객체를 수정하지 않고 새로운 정렬된 리스트를 반환합니다.
    • 세 개의 선택적 인자를 받습니다: key (정렬 순서를 사용자 정의하는 함수), reverse (내림차순으로 정렬할지 여부를 지정하는 부울 값), 반복 가능한 객체 (정렬할 반복 가능한 객체).
  5. join(반복 가능한 객체):
    • join()은 파이썬의 문자열 메소드로, 반복 가능한 객체(예: 리스트)의 요소들을 하나의 문자열로 연결합니다.
    • 이터러블의 각 요소를 호출된 문자열과 결합하여 하나의 문자열을 반환합니다.
# Sample list of numbers
numbers = [5, 2, 8, 1, 3, 9, 4, 7, 6]

# Example function for filtering odd numbers
def is_odd(n):
    return n % 2 != 0

# Example function for doubling numbers
def double(n):
    return n * 2

# Filter odd numbers using filter
odd_numbers = list(filter(is_odd, numbers))
print("Odd numbers:", odd_numbers)

# Double all numbers using map
doubled_numbers = list(map(double, numbers))
print("Doubled numbers:", doubled_numbers)

# Sort numbers in ascending order using sort
ascending_sorted = sorted(numbers)
print("Ascending order:", ascending_sorted)

# Sort numbers in descending order using sort with reverse parameter
descending_sorted = sorted(numbers, reverse=True)
print("Descending order:", descending_sorted)

# Alternatively, you can use toSorted for sorting and join to concatenate elements of a list into a string
sorted_numbers = ' '.join(map(str, sorted(numbers)))
print("Sorted numbers:", sorted_numbers)
728x90