<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src = "http://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
<script>
const books =[{
name : 'learn python',
price : 10000,
publisher : 'media'
}, {
name : 'html5 web programming',
price : 20000,
publisher : 'academy'
},{
name : 'machine learn',
price : 30000,
publisher : 'wiki'
},
{
name : 'deep-learning',
price : 25000,
publisher : 'wiki'
}]
const output = _.sortBy(books, (book) => book.price)
console.log(JSON.stringify(output, null, 2))
</script>
</head>
<body>
</body>
</html>
### How the Script Works
1. **Loading Lodash**: The script tag with the `src` attribute includes Lodash from a CDN (Content Delivery Network), making the Lodash functions available for use in the script that follows.
2. **Array of Books**: An array named `books` is declared, containing objects. Each object represents a book, with properties for the book's name (`name`), price (`price`), and publisher (`publisher`).
3. **Sorting Books by Price**: The Lodash function `_.sortBy` is used to sort the `books` array. The sorting criterion is the book's price, as indicated by the callback function `(book) => book.price` passed to `_.sortBy`. This function returns a new array sorted in ascending order of book prices.
4. **Logging the Sorted Array**: The sorted array is converted to a JSON string with `JSON.stringify(output, null, 2)` for readability, including indentation for better visualization, and then logged to the console.
### Example Output
The console output will display the `books` array sorted by price in ascending order, formatted for readability:
```
[
{
"name": "learn python",
"price": 10000,
"publisher": "media"
},
{
"name": "html5 web programming",
"price": 20000,
"publisher": "academy"
},
{
"name": "deep-learning",
"price": 25000,
"publisher": "wiki"
},
{
"name": "machine learn",
"price": 30000,
"publisher": "wiki"
}
]
```
### Summary
This HTML document effectively demonstrates the use of Lodash to manipulate and process data collections in JavaScript, specifically showcasing how to sort an array of objects by a property. The inclusion of Lodash via CDN is a common practice to utilize its extensive utilities without the need for local installation or bundling, enhancing web development efficiency.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
method) JSON.parse() method (0) | 2025.01.20 |
---|---|
method) JSON.stringify() method (0) | 2025.01.19 |
method) map() method (0) | 2025.01.17 |
method) Math.random() method (0) | 2025.01.16 |
method) prototype method (1) | 2025.01.15 |