arr.sort() : 배열 재정렬, 배열 자체가 변경됨
let arr1 = [1,5,4,2,3]
arr1.sort()
console.log(arr1)
let arr2 = ['a','e','d','b','c']
arr2.sort()
console.log(arr2)
let arr3 = [27,8,5,13]
arr3.sort()
console.log(arr3)
arr3.sort((a,b) => {
return a-b
})
console.log(arr3)
Lodash : 기능을 모아놓은 라이브러리
let arr3 = [27,8,5,13]
_.sortBy(arr3)
console.log(arr3)
reduce
let arr = [1,2,3,4,5]
let result = 0
arr.forEach((num) => {
result+=num
})
console.log(result)
const result = arr.reduce((prev, cur) => {
return prev+cur
},0)
console.log(result)
예제
let userList = [
{ name:'A', age:30 },
{ name:'B', age:10 },
{ name:'C', age:27 },
{ name:'D', age:18 },
{ name:'E', age:42 },
{ name:'F', age:3 },
]
let result = userList.reduce((prev, cur) => {
if(cur.age > 19){
prev.push(cur.name)
}
return prev;
},[])
let totalAge = userList.reduce((prev, cur) => {
return prev.age += cur.age
}, 0)