개발자
obj라는 객체를 아래와 같이 정렬시키려고 합니다 정렬 기준은 각각의 요소중 total을 기준으로 내림차순 정렬해야합니다 아무리해도 정렬하고 객체로 만드는 과정중에 정렬이 풀리는데 혹시 하는방법 아시는분 있나요..? -입력- const obj = { yearMonth: "2023-10", 호랑이: {cat: '호랑이', total: 2, ycnt: 2, ncnt: 0}, 사자: {cat: '사자', total: 56, ycnt: 46, ncnt: 10}, 말: {cat: '말', total: 54, ycnt: 39, ncnt: 15}, 고양이: {cat: '고양이', total: 7, ycnt: 6, ncnt: 1}, 악어: {cat: '악어', total: 17, ycnt: 12, ncnt: 5}, 사슴: {cat: '사슴', total: 41, ycnt: 37, ncnt: 4}, 곰: {cat: '곰', total: 89, ycnt: 77, ncnt: 12}, 기린: {cat: '기린', total: 10, ycnt: 8, ncnt: 2}, 치타: {cat: '치타', total: 9, ycnt: 6, ncnt: 3}, 코끼리: {cat: '코끼리', total: 22, ycnt: 18, ncnt: 4}, 강아지: {cat: '강아지', total: 48, ycnt: 42, ncnt: 6}, } -출력- { yearMonth: "2023-10" 곰: {cat: '곰', total: 89, ycnt: 77, ncnt: 12}, 사자: {cat: '사자', total: 56, ycnt: 46, ncnt: 10}, 말: {cat: '말', total: 54, ycnt: 39, ncnt: 15}, 강아지: {cat: '강아지', total: 48, ycnt: 42, ncnt: 6}, 사슴: {cat: '사슴', total: 41, ycnt: 37, ncnt: 4}, 코끼리: {cat: '코끼리', total: 22, ycnt: 18, ncnt: 4}, 악어: {cat: '악어', total: 17, ycnt: 12, ncnt: 5}, 기린: {cat: '기린', total: 10, ycnt: 8, ncnt: 2}, 치타: {cat: '치타', total: 9, ycnt: 6, ncnt: 3}, 고양이: {cat: '고양이', total: 7, ycnt: 6, ncnt: 1}, 호랑이: {cat: '호랑이', total: 2, ycnt: 2, ncnt: 0}, }
답변 2
익명
작성자
2024년 05월 13일
넵 출력은 정답 결과값을 제가 그냥 적은거고 입력을 받으면 출력(정답결과값)을 하는 코드를 작성하는게 목표입니다!
문정동개발자
프론트엔드 • 2024년 05월 13일
function sortObjByTotal(obj){ // 기존 오브젝트에서 sorting할 부분만 배열로 변경 const arr = Object.keys(obj).reduce((res,curr)=>{ if(obj[curr]['cat'] != undefined && obj[curr]['total'] != undefined && obj[curr]['ycnt'] != undefined && obj[curr]['ncnt'] != undefined){ return [...res,obj[curr]] }else{ return res; } },[]) //sorting arr.sort((a,b)=>b['total'] - a['total']); //sorting된 배열을 다시 오브젝트로 변경 const res = { yearMonth:obj['yearMonth'] } arr.forEach(v=>res[v['cat']] = v) return res; } 더 좋은 방법이 많을 수 있습니다.
문정동개발자
프론트엔드 • 2024년 05월 13일
gpt는 이렇게 알려주네요 좀더 깔끔한 것 같습니다 function sortObjectByTotal(obj) { // yearMonth을 제외한 나머지 속성들을 total 기준으로 정렬 const sortedEntries = Object.entries(obj) .filter(([key, value]) => key !== 'yearMonth') .sort((a, b) => b[1].total - a[1].total); // yearMonth을 유지하고, 정렬된 항목을 새 객체에 추가 const sortedObj = { yearMonth: obj.yearMonth }; sortedEntries.forEach(([key, value]) => { sortedObj[key] = value; }); return sortedObj; }
익명
작성자
2024년 05월 13일
답변 너무 감사드립니다. 집가는 중인데 제가 해보고 다시 말씀드릴게요!
익명
작성자
2024년 05월 13일
이것도 정렬 잘 되는 것 같네요 감사합니다!! ㅠㅠ
.
1const arr = Object.entries(obj).filter(([key, value]) => key !== 'yearMonth').sort((a, b) => b[1].total - a[1].total);
2
3const sortedObj = Object.fromEntries([['yearMonth', obj.yearMonth], ...arr]);
익명
작성자
2024년 05월 13일
답변 너무 감사드립니다. 제가 해보고 결과 알려드릴게욤!
익명
작성자
2024년 05월 13일
해봤는데 정렬 안 된 입력결과 그대로 나옵니다 ㅠㅠ
정 훈
FE • 2024년 05월 13일
제가 해봤을 때 정렬되던데 안되시나요 ?
익명
작성자
2024년 05월 13일
const obj = { yearMonth: "2023-10", 호랑이: { cat: "호랑이", total: 2, ycnt: 2, ncnt: 0 }, 사자: { cat: "사자", total: 56, ycnt: 46, ncnt: 10 }, 말: { cat: "말", total: 54, ycnt: 39, ncnt: 15 }, 고양이: { cat: "고양이", total: 7, ycnt: 6, ncnt: 1 }, 악어: { cat: "악어", total: 17, ycnt: 12, ncnt: 5 }, 사슴: { cat: "사슴", total: 41, ycnt: 37, ncnt: 4 }, 곰: { cat: "곰", total: 89, ycnt: 77, ncnt: 12 }, 기린: { cat: "기린", total: 10, ycnt: 8, ncnt: 2 }, 치타: { cat: "치타", total: 9, ycnt: 6, ncnt: 3 }, 코끼리: { cat: "코끼리", total: 22, ycnt: 18, ncnt: 4 }, 강아지: { cat: "강아지", total: 48, ycnt: 42, ncnt: 6 }, }; const arr = Object.entries(obj) .filter(([key, value]) => key !== "yearMonth") .sort((a, b) => b[1].total - a[1].total); const sortedObj = Object.fromEntries([["yearMonth", obj.yearMonth], ...arr]); console.log("sortedObj", sortedObj); -------------------------------------------------------- 콘솔 결과 ↓↓↓↓↓ sortedObj {yearMonth: '2023-10', 곰: {…}, 사자: {…}, 말: {…}, 강아지: {…}, …} yearMonth: "2023-10" 강아지: {cat: '강아지', total: 48, ycnt: 42, ncnt: 6} 고양이: {cat: '고양이', total: 7, ycnt: 6, ncnt: 1} 곰: {cat: '곰', total: 89, ycnt: 77, ncnt: 12} 기린: {cat: '기린', total: 10, ycnt: 8, ncnt: 2} 말: {cat: '말', total: 54, ycnt: 39, ncnt: 15} 사슴: {cat: '사슴', total: 41, ycnt: 37, ncnt: 4} 사자: {cat: '사자', total: 56, ycnt: 46, ncnt: 10} 악어: {cat: '악어', total: 17, ycnt: 12, ncnt: 5} 치타: {cat: '치타', total: 9, ycnt: 6, ncnt: 3} 코끼리: {cat: '코끼리', total: 22, ycnt: 18, ncnt: 4} 호랑이: {cat: '호랑이', total: 2, ycnt: 2, ncnt: 0} 저는 크롬브라우저 기준으로 콘솔에 찍힌거보면 total이 내림차순으로 정렬 안되어있네요 ㅠㅠ
정 훈
FE • 2024년 05월 14일
브라우저 콘솔창에서는 펼쳤을 때 정렬이 안된 것 처럼 보이네요. {yearMonth: '2023-10', 곰: {…}, 사자: {…}, 말: {…}, 강아지: {…}, …} 이 부분을 보시면 정렬이 된건 맞는 것 같습니다. vscode 에서도 정렬된 값으로 나와요
익명
작성자
2024년 05월 14일
오?? 축약부분이랑 펼쳤을때랑 다르네요? 오호 감사합니다 다시해볼게욤
지금 가입하면 모든 질문의 답변을 볼 수 있어요!
현직자들의 명쾌한 답변을 얻을 수 있어요.
이미 회원이신가요?
커리어리 AI 봇
GPT가 달아주는 답변입니다.
2024년 05월 13일
자바스크립트에서 객체는 프로퍼티의 키에 따라 정렬되는 것이 아니라, 입력한 순서를 유지합니다. 그렇기 때문에 기존의 obj를 배열로 변환하고 total 값에 따라 정렬한 후 다시 객체로 변환해주어야 합니다. 먼저 `yearMonth` 값을 저장하고 삭제한 후, 배열로 변경하고 내림차순 정렬을 한 후에 다시 객체로 변환하는 코드입니다: ```javascript const yearMonth = obj.yearMonth; // yearMonth 값을 저장 delete obj.yearMonth; // obj에서 yearMonth 프로퍼티 삭제 let arr = Object.keys(obj).map((key) => obj[key]); // 객체를 배열로 변환 arr.sort((a, b) => b.total - a.total); // total값 기준으로 내림차순 정렬 let sortedObj = {yearMonth}; // yearMonth 포함된 새 객체 생성 arr.forEach(item => { sortedObj[item.cat] = item; // 새 객체에 요소 추가 }); ``` 이제 `sortedObj`는 제대로 정렬된 상태입니다. 이 접근 방식은 자바스크립트에서 객체가 본래 가지고 있는 특성을 우회하기 때문에 실제 실행 환경에서 사용할 때 주의가 필요합니다.
지금 가입하면 모든 질문의 답변을 볼 수 있어요!