[TIL] 221013

EllaDev·2022년 10월 13일
0

Today I Learn

목록 보기
1/13

Today I Learn

  • Array.sort()
  • String.spilt()
  • Array.join()

1.Javascript

1.1. Method

1.1.1. Array.sort()

매개변수 / 반환값

	arr.sort(['compareFunction'])
/*
    => Q1.그럼 숫자나 객체를 문자로 바꾸어서 유니코드에 따라 정렬한다는데... 그렇다면 우선순위는 어떻게 되는가?
     */
	 // Answer1
	let arr1 = [1,10,2,31234,'안녕', {a:1, b:'a'}]
    arr1.sort() // [1, 10, 2, 31234, {a:1, b:'a'}, '안녕']
	

  1. 매개변수(compareFunction) :
  • 매개변수를 생략하면 각 요소를 문자열 변환하여 유니코드 코드 포인트 순서로 문자열을 비교하여 정렬한다.
    Ex1) 문자 : ['체리', '바나나'] -> ['바나나', '체리']
    Ex2) 숫자 : 숫자는 문자로 변환되어 정렬되므로 [9,80] -> [80,9]
  1. 반환값(return) :
  • 기존 배열이 정렬되는 것이므로 불변성이 지켜지지 않는다. 복사본 없다.

설명

// Compare 함수의 동작
  function compare(a, b) {
    if (a < b) {
      return -1;
    }
    if (a > b) {
      return 1;
    }
    /*
    a와 b가 같을 때 => a와 b를 서로에 대해 변경하지 않고 모든 다른 요소에 대해 정렬(ECMAscript 표준은 이러한 동작을 보장하지 않으므로 모든 브라우저(예 : Mozilla 버전은 적어도 2003 년 이후 버전 임)가 이를 존중하지는 않는다.)
    */
    return 0;
  }
  1. 문자열 대신 숫자를 비교
// 오름차순 정렬
function compareNumbers(a, b) {
  return a - b;
}

let numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]
  1. 객체 : 해당 속성 중 하나의 값을 기준으로 정렬
let items = [
  { name: 'Edward', value: 21 },
  { name: 'Sharpe', value: 37 },
  { name: 'And', value: 45 },
  { name: 'The', value: -12 },
  { name: 'Magnetic', value: 13 },
  { name: 'Zeros', value: 37 }
];

// value 기준으로 정렬
items.sort(function (a, b) {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

// name 기준으로 정렬
items.sort(function(a, b) {
  let nameA = a.name.toUpperCase(); // ignore upper and lowercase
  let nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }
  // 이름이 같을 경우
  return 0;
});

예제
1. 배열만들기 / 정렬

function compareNumbers(a, b) {
  return a - b;
}

/* 문자열 배열 정렬*/
let stringArray = ['Blue', 'Humpback', 'Beluga'];

console.log('stringArray:', stringArray.join());
console.log('Sorted:', stringArray.sort());

//stringArray: Blue,Humpback,Beluga
//Sorted: Beluga,Blue,Humpback

/* 숫자 배열 정렬 */
// 1. 문자열로 되어있는 숫자를 정렬
let numericStringArray = ['80', '9', '700']

console.log('numberArray:', numberArray.join());
console.log('Sorted without a compare function:', numberArray.sort());
console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));

// numberArray: 40,1,5,200
// Sorted without a compare function: 1,200,40,5 => 제대로 안됨
// Sorted with compareNumbers: 1,5,40,200 => 오름차순

//2. 숫자로만 되어있는 정렬
let numberArray = [40, 1, 5, 200];

console.log('numericStringArray:', numericStringArray.join());
console.log('Sorted without a compare function:', numericStringArray.sort());
console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));

// numericStringArray: 80,9,700
// Sorted without a compare function: 700,80,9 => 내림 차순
// Sorted with compareNumbers: 9,80,700 => 오름 차순

/* 숫자와 문자열이 혼합되어있는 배열 */
let mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];

console.log('mixedNumericArray:', mixedNumericArray.join());
console.log('Sorted without a compare function:', mixedNumericArray.sort());
console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));

// mixedNumericArray: 80,9,700,40,1,5,200
// Sorted without a compare function: 1,200,40,5,700,80,9
// Sorted with compareNumbers: 1,5,9,40,80,200,700
  1. map을 사용한 정렬 => 좀더 이해가 필요!!
    compareFunction은 배열 내의 요소마다 여러 번 호출되므로 성능적인 면이 저하될 수 있다. 그러므로 compareFunction이 복잡해지고, 정렬할 요소가 많아질 경우, map을 사용한 정렬하면 더 좋다. 이 방법은 임시 배열을 하나 만들어서 여기에 실제 정렬에 사용할 값만을 뽑아서 넣어서 이를 정렬하고, 그 결과를 이용해서 실제 정렬을 하는 것이다.

Ref
MDN Document


1.1.2. String.spilt()

Ref
MDN Document


1.1.3. Array.join()


Ref
MDN Document

profile
Frontend Developer

0개의 댓글