Array.sort

김명성·2022년 2월 2일
0

자바스크립트

목록 보기
6/26

sort : 문자, 숫자를 정렬하기 위해 사용되는 Array의 prototype인 sort이다.

let 어레이 = [7,6,2423,325325,123123,2856];
어레이.sort(function(a,b){
    return a - b;
});
  • 오름차순 :여기서 a-b가 양수면 a를 왼쪽으로 b를 오른쪽으로 정렬하면서 인덱스에 모든 수를 뺄셈함.
  • 내림차순 : b - a;
  • 가나다순 : 그냥 array.sort() , 또는 a > b와 같은 부등호와 if문을 통해 true면 -1 false 면 1을 넣어 정렬할 수 있다.
  • 가나다역순 : array.sort().reverse()

let 어레이 = [1,2,3]
let 어레이2 = [...어레이]

// [...spread]operator  값을 공유하지 않고 별개의 배열을 생성하게 해준다.

가격필터 만들기

요구사항 : 가나다순으로 만들기 기능제작 , 필터기능 5만원이하 필터버튼 기능제작 6,7만원 짜리 div는 사라져야 함 HTML 을 동적으로 만듬. 필터버튼 누르면 생성

HTML 동적생성 - > 템플릿을 만들어 작성.
var 출석부 = ['흥민', '영희', '철수', '재석'];

function 이름찾기(구멍) {
  출석부.forEach((x) => {
    if (x == 구멍) {
      console.log('있어요');
    }
  });
}
이름찾기('철수');

function 구구단() {
  for (i = 2; i < 10; i++) {
    for (j = 1; j < 10; j++) {
      console.log(i * j);
    }
  }
}

문제 : 7~11월 실적, 평균 월 목표 판매량을 입력하면 12월 목표 실적(임의의 숫자)을 계산해주는 프로그램.


내가 생각한 해결 방안 : 12월목표실적*6 - 판매실적어레이의 각 요소 값을 더한 값.


let 김철수 = [150, 100, 180, 120, 200];
let 박재성 = [150, 90, 110, 170, 100];
let 김영희 = [150, 110, 120, 170, 150];

reduce 없이 배열 내 요소들의 합 구하기

javascript sum elements in array

1.forEach함수를 통한 계산
function arrSum(arr){
total = 0;
arr.forEach(function(key){
total = total + key;
});
return total;
}
function 목표량계산기(영업사원이름,목표판매량){
total = 0;
영업사원이름.forEach((key) =>{
total = total + key;
});
return (목표판매량*6)-total;
}

  1. for문 사용 사용

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

function 목표량계산기(영업사원이름, 목표판매량) {
합계 = 0;
for (i = 0; i < 영업사원이름.length; i++) {
합계 += 영업사원이름[i];
}
return (목표판매량 * 6) - 합계;
}

가나다 역순으로 배열 정렬하기

javascript how to reverse sort string in array

https://stackoverflow.com/questions/52030110/sorting-strings-in-descending-order-in-javascript-most-efficiently


if you consider

obj.sort().reverse();
VS

obj.sort((a, b) => (a > b ? -1 : 1))
VS

obj.sort((a, b) => b.localeCompare(a) )
The performance winner is : obj.sort().reverse().

Testing with an array of 10.000 elements, obj.sort().reverse() is faster than obj.sort( function ) (except on chrome), and obj.sort( function ) (using localCompare).

적용
let 어레이 = ['김치','치즈','소고기','바질','파'];
어레이.sort().reverse();
(5) ['파', '치즈', '소고기', '바질', '김치']

배열 안 객체 속 특정 키의 속성값 찾기.
javascript find objects values in array

https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array

Here is a shorter way of achieving it:

let result = objArray.map(a => a.foo);
OR

let result = objArray.map(({ foo }) => foo)
You can also check Array.prototype.map().

map을 통해 배열 내 객체들의 price value를 찾고, 그것을 오름차순으로 정렬

var products = [
{ id: 0, price: 70000, title: 'Blossom Dress' },
{ id: 1, price: 50000, title: 'Springfield Shirt' },
{ id: 2, price: 60000, title: 'Black Monastery' },
];
오름차순
products.map(a => a.price).sort((a,b) => { return b - a });
(3) [70000, 60000, 50000]

내림차순
products.map(a => a.price).sort((a,b) => { return a - b });
(3) [50000, 60000, 70000]

뽑아낸 결과를 다른 변수에 담아 지정

let result = products.map(a => a.price).sort((a,b) => { return b - a });

버튼을 클릭하면 , result[i] 순서대로 가격을 정렬 시킴.

문제는 제품과 가격명이 같이 움직어야 하는데.. 가격만 추출하여 같이 움직일 수 없음...

객체를 분해하지 않고 price 순서대로 정렬할 수 있는 방법??

다시 처음으로 돌아가 배운 sort를 통해 할 수 있는 방법 찾기..

products.sort((a,b) =>{
products[a].price - products[b].price})

를 해보았으나 a,b가 인덱스가 아니기에 안됨 ㅎㅎ

a,b에는 배열의 값이 들어가니까.. 음
a.price - b.price 도 안됨..

products.sort()를 하면 배열에 입력된 순서대로 정렬됨.
products.sort().reverse()는 배열에 입력된 역순대로 정렬 됨.
기준점을 배열의 price로만 할 수 있다면 쉽게 풀 수 있을텐데..

products.sort((a,b) => { console.log(a.price); });를 해보니
a.price는 50000,60000 2개의 값을 갖고 있었음
b.price는 70000,50000 2개의 값.
products.sort((a,b) => { console.log(a.price - b.price); });는
-20000 , 10000

함수는 정상적으로 계산하는데 왜 안되는 걸까?

아 최종 값을 반환해야하는 return을 빼먹음!

products.sort((a,b) => { return a.price - b.price; });

0: {id: 1, price: 50000, title: 'Springfield Shirt'}
1: {id: 2, price: 60000, title: 'Black Monastery'}
2: {id: 0, price: 70000, title: 'Blossom Dress'}

드디어 정상적으로 값을 순서대로 정렬할 수 있게 되었다!

그럼 이제, 버튼을 누르면 작성한 함수대로 정렬해달라고 말해야한다.
버튼의 클래스는 .sort-btn

$('.sort-btn').click(() => {
    
  priceSort = products.sort((a, b) => {
    return a.price - b.price;
  });
  for (i = 0; i < priceSort.length; i++) {
    $('.card-body h5').eq(i).html(priceSort[i].title);
    $('.card-body p').eq(i).html(`가격 : ${priceSort[i].price}`);
  }
});

정상작동 !!

https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers

0개의 댓글