Programming/JavaScript

[JavaScript] ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ Object array ํŠน์ • ํ•„๋“œ ๊ธฐ์ค€ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜๋Š” ๋ฐฉ๋ฒ•

yuri lee 2023. 1. 21. 15:50
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” JavaScript ์—์„œ Object array ๋ฅผ ์ •๋ ฌํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

How to do

์•„๋ž˜์˜ ์˜ค๋ธŒ์ ํŠธ ์–ด๋ ˆ์ด๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ด…์‹œ๋‹ค. 

const objectArray = [
    { name: 'aa', year: 2008 },
    { name: 'bb', year: 2004 },
    { name: 'cc', year: 2003 },
    { name: 'dd', year: 1996 },
    { name: 'ee', year: 1995 },
    { name: 'ff', year: 2015 }
];

 

javascript์˜ sort() ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด์„œ year ํ•„๋“œ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์„ ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

objectArray.sort((x, y) => x.year - y.year);
console.log(objectArray);

 

์ฝ”๋“œ ์‹คํ–‰ ๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. 

[
    {
        "name": "ee",
        "year": 1995
    },
    {
        "name": "dd",
        "year": 1996
    },
    {
        "name": "cc",
        "year": 2003
    },
    {
        "name": "bb",
        "year": 2004
    },
    {
        "name": "aa",
        "year": 2008
    },
    {
        "name": "ff",
        "year": 2015
    }
]


https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

๋ฐ˜์‘ํ˜•