Created
March 25, 2020 17:11
-
-
Save monbang/f155aa1e399955eff33121dd0c27e773 to your computer and use it in GitHub Desktop.
js array functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// filter active items | |
const filtered = items.filter(item => item.isActive == 10); | |
// map name and title | |
const mapped = items.map(item => `${item.name} ${item.title}`); | |
// sort the item by year, oldest to yongest | |
const sorted = items.sort((a, b) => a.year > b.year ? 1 : -1); | |
// calculate total | |
const totalAmount = items.reduce((total, item) => { | |
return total += (item.price + 10); | |
}, 0); | |
// sort by years lived | |
const oldest = items.sort((a, b) { | |
const lastGuy = a.passed - a.year; | |
const nextGuy = b.passed - b.year; | |
return lastGuy > nextGuy ? -1 : 1; | |
}); | |
// get all words by de from webpage | |
const category = document.querySelector('.mw-category'); | |
const links = Array.from(category.querySelectorAll('a')); | |
const de = links | |
.map(link => link.textContent) | |
.filter(streetName => streetName.includes('de')); | |
// sort on lastname | |
const people = ['Riju, Das', 'Dhruba Das']; | |
const sorted = people.sort((lastOne, nextOne) => { | |
const [aLast, aFirst] = lastOne.split(', '); | |
const [bLast, bFirst] = nextOne.split(', '); | |
return aLast > bLast ? 1 : -1; | |
}); | |
console.table(sorted); | |
// count instances | |
const products = ['car', 'bike', 'car', 'car', 'bike', 'truck', 'truck', 'van']; | |
const total = products.reduce((obu, item) { | |
if (!obj[item]) { | |
obj[item] = 0; | |
} | |
obj[item]++; | |
return obj; | |
}, {}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment