Skip to content

Instantly share code, notes, and snippets.

@monbang
Created March 25, 2020 17:11
Show Gist options
  • Save monbang/f155aa1e399955eff33121dd0c27e773 to your computer and use it in GitHub Desktop.
Save monbang/f155aa1e399955eff33121dd0c27e773 to your computer and use it in GitHub Desktop.
js array functions
// 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