1. slice

slice(start?: number, end?: number): T[];

Returns a copy of a section of an array.

(배열 섹션의 복사본을 반환합니다.)

For both start and end, a negative index can be used to indicate an offset from the end of the array.

(시작과 끝 모두에 대해 음수 인덱스를 사용하여 배열 끝에서 오프셋을 나타낼 수 있습니다.) ★

For example, -2 refers to the second to last element of the array.

(예를 들어 -2는 배열의 마지막에서 두 번째 요소를 나타냅니다.)

@param start The beginning index of the specified portion of the array.

(@param start 는 배열에서 지정된 부분의 시작 인덱스입니다.)

If start is undefined, then the slice begins at index 0.

(start가 정의되지 않은 경우 슬라이스는 인덱스 0에서 시작합니다.)

@param end The end index of the specified portion of the array. This is exclusive of the element at the index 'end'.

(@param end 는 배열에서 지정된 부분의 끝 인덱스입니다. 이것은 반환 시 'end'의 요소를 제외합니다.)

If end is undefined, then the slice extends to the end of the array.

(end가 정의되지 않은 경우 슬라이스는 배열의 끝까지 확장됩니다.)

start(n) 부터 ~ end(n-1) 까지

's'  'l'  'i' 'c'  'e'

0   1   2    3   4

-5  -4  -3  -2  -1

*// 원본 배열은 유지되고 해당 index의 데이터만 쏙 빼온다.*
const arrslice        = ['s','l','i','c','e'];
const arrsliceResult1 = arrslice.slice(0, 1);
const arrsliceResult2 = arrslice.slice(0, 3);
const arrsliceResult3 = arrslice.slice(2, 4);
const arrsliceResult4 = arrslice.slice(0, -1);
const arrsliceResult5 = arrslice.slice(0, -3);
const arrsliceResult6 = arrslice.slice(1, -3);
const arrsliceResult7 = arrslice.slice(2);
const arrsliceResult8 = arrslice.slice(-3);
const arrsliceResult9 = arrslice.slice(-5, -1);
const arrsliceResult10 = arrslice.slice(-5);
*// 결과*
console.log(arrsliceResult1);  // ["s"]                = start_index:  0 / end_index:  1
console.log(arrsliceResult2);  // ["s", "l", "i"]      = start_index:  0 / end_index:  3
console.log(arrsliceResult3);  // ["i", "c"]           = start_index:  2 / end_index:  4
console.log(arrsliceResult4);  // ["s", "l", "i", "c"] = start_index:  0 / end_index: -1 (4)
console.log(arrsliceResult5);  // ["s", "l"]           = start_index:  0 / end_index: -3 (2)
console.log(arrsliceResult6);  // ["l"]                = start_index:  1 / end_index: -3 (4)
console.log(arrsliceResult7);  // ["i", "c", "e"]      = start_index:  2
console.log(arrsliceResult8);  // ["i", "c", "e"]      = start_index: -3 (2)
console.log(arrsliceResult9);  // ["s", "l", "i", "c"] = start_index: -5 (0) / end_index: -1 (4)
console.log(arrsliceResult10); // ["s", "l", "i", "c", "e"] = start_index: -5 (0)

<aside> 💡 인덱스로 양수든 음수든 start에 지정된 인덱스에 해당하는 값의 오른쪽으로 탐색한다.

</aside>

  1. sort

sort(compareFn?: (a: T, b: T) => number): this;

compareFn -> compareFunction (callback 함수)

Sorts an array in place.

(배열을 제자리에서 정렬합니다.)

This method mutates the array and returns a reference to the same array.

(이 메서드는 배열을 변경하고, 동일한 배열에 대한 참조를 반환합니다.)

@param compareFn Function used to determine the order of the elements.

(@param compareFn 함수는 요소의 순서를 결정하는 데 사용되는 함수입니다.)

It is expected to return a negative value if first argument is less than second argument, zero if they're equal and a positive value otherwise. If omitted, the elements are sorted in ascending, ASCII character order.

(첫 번째 인수가 두 번째 인수보다 작으면 음수 값을 반환하고 → return 음수

같으면 0을 반환하고                                     → return 0

그렇지 않으면 양수 값을 반환합니다.                      → return 양수

생략하면 요소가 ASCII 문자 오름차순으로 정렬됩니다.)

[11,2,22,1].sort((a, b) => a - b);

[11,2,22,1].sort(function(a, b){

return a - b

});

⚠️ 정렬한 배열, 원 배열이 정렬되는 것에 유의하세요. 복사본이 만들어지는 것이 아닙니다.

const arrsort1 = ['kht', '28', '029', 'db'];
const arrsort2 = ['^', 5, 4, 3, 2, 1];
const arrsort3 = [10, 1, 2, 3, 9, 5];
// 결과1
console.log(arrsort1.sort());                // ["029", "28", "db", "kht"]
console.log(arrsort1.sort((a, b) => a - b)); // ["28", "029", "db", "kht"]
// 결과2
console.log(arrsort2.sort());                // [1, 2, 3, 4, 5, "^"]
console.log(arrsort2.sort((a, b) => a - b)); // [1, 2, 3, 4, 5, "^"]
// 결과3
console.log(arrsort3.sort((a, b) => {
    console.log('a:' + a);
    console.log('b:' + b);
    console.log(a - b);
    return a - b;
}));
/**
 *                                    b   a  (순차정렬진행?)
 *                               --> [10, 1, 2, 3, 9, 5]
 * a:1 / b:10 = return a-b = -9  --> [1, 10, 2, 3, 9, 5]
 * a:2 / b:1  = return a-b =  1  --> [1, 10, 2, 3, 9, 5]
 * a:2 / b:10 = return a-b = -8  --> [1, 2, 10, 3, 9, 5]
 * a:2 / b:1  = return a-b =  1  --> [1, 2, 10, 3, 9, 5]
 * a:3 / b:2  = return a-b =  1  --> [1, 2, 10, 3, 9, 5]
 * a:3 / b:10 = return a-b = -7  --> [1, 2, 3, 10, 9, 5]
 * a:9 / b:3  = return a-b =  6  --> [1, 2, 3, 10, 9, 5]
 * a:9 / b:10 = return a-b = -1  --> [1, 2, 3, 9, 10, 5]
 * a:5 / b:3  = return a-b =  2  --> [1, 2, 3, 9, 10, 5]
 * a:5 / b:10 = return a-b = -5  --> [1, 2, 3, 9, 5, 10]
 * a:5 / b:9  = return a-b = -4  --> [1, 2, 3, 5, 9, 10]
 */

⚠️ sort(); 로 하면 문자열(사전 순서)의 순서로 정렬된다.

const arr = [11, 10, 3, 4, 5, "4"];
const result = arr.sort(); // 10 부터 문자열의 형태로 정렬된다.
console.log(result);
/** 
 * 결과
 * [10, 11, 3, 4, "4", 5]
 * -> (10이상)문자열은 숫자보다 앞으로 온다.
*/

  1. splice

splice(start: number, deleteCount?: number): T[];

Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.

(배열에서 요소를 제거하고 필요한 경우 해당 위치에 새 요소를 삽입하여 삭제 된 요소를 반환합니다.)

@param start The zero-based location in the array from which to start removing elements.

(@param start 는 요소 제거를 시작할 배열의 0부터 시작하는 위치입니다.)

@param deleteCount The number of elements to remove.

(@param deleteCount 는 제거 할 요소의 수입니다.)

@returns An array containing the elements that were deleted.

(@returns 는 삭제 된 요소를 포함하는 배열입니다.)

★★★ splice 는 제거된 요소를 배열형태로 반환하고, shift 는 요소로만 반환 된다.

const arrsplice = ['a', 'b', 'c', 'd'];
// 결과
const arrspliceR = arrsplice.splice(1, 2); // index 1 에서 부터 2개 요소를 제거
console.log(arrspliceR); // ["b", "c"] -> 삭제 된 요소를 반환
console.log(arrsplice);  // ["a", "d"]

// ------------------------------------

const arrsplice2 = ['a', 'b', 'c', 'd'];
// 결과
const arrspliceR = arrsplice2.splice(1, 2)[0]; // index 1 에서 부터 2개 요소를 제거후
																							// 제거된 요소 ["b", "c"] 에서 "b" 를 반환
																							// [1] 이면 "c" 반환
console.log(arrspliceR); // ["b"] -> 삭제 된 요소를 반환
  1. splice

splice(start: number, deleteCount: number, ...items: T[]): T[];

@param items Elements to insert into the array in place of the deleted elements.

(@param items 는 삭제 된 요소 대신 배열에 삽입 할 요소입니다.)

반드시 삭제될 인자가 존재하여야, 삽입 할 수 있다.

splice(0, 0, 't') 처럼 사용이 가능하며, 삭제되는 요소가 1개라도 있어야 한다는 의미가 아니라, 인자에 값이 존재하여야 한다.

const arrsplice2 = ['a', 'b', 'c', 'd'];
// 결과
arrsplice2.splice(0, 1, 't', 'h'); // index 0 에서 부터 1개 요소를 제거 후 제거된 곳에 't', 'h' 추가
console.log(arrsplice2); //  ["t", "h", "b", "c", "d"]
  1. IndexOf

indexOf(searchElement: T, fromIndex?: number): number;

배열의 맨 앞에서 부터 찾기 시작하여, 먼저 존재하는 해당 값을 찾아, 해당 인덱스를 반환한다.

*배열 뿐만 아니라, 문자열에서도 indexOf 함수 사용 가능*

(정방향으로 찾기)

Returns the index of the first occurrence of a value in an array, or -1 if it is not present.

(배열에서 값이 처음 나타나는 인덱스를 반환하거나없는 경우 -1을 반환합니다.)

@param searchElement The value to locate in the array.

(@param searchElement 는 배열에서 찾을 값입니다.)

@param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.

(@param fromIndex 는 검색을 시작할 배열 인덱스입니다. fromIndex가 생략되면 검색은 인덱스 0에서 시작합니다.)

const arrindexof = ['a', 'b', 'c', 'd'];
// 배열 앞에서 부터 찾기시작
// 결과1
const index_num  = arrindexof.indexOf('c');
console.log(index_num);  // 2
// 결과2
const index_num2 = arrindexof.indexOf('c', 1);
console.log(index_num2); // 2
// 결과3
const index_num3 = arrindexof.indexOf('c', -1);
console.log(index_num3); // -1
// 결과4
const index_num4 = arrindexof.indexOf('e');
console.log(index_num4); // -1

// 문자열 indexOf
const strIndex = 'Loyal football Team play'.indexOf('ball');
console.log(strIndex); // 10 (ball 이 존재하는 최초위치를 반환한다.)