Skip to content

Instantly share code, notes, and snippets.

@Sstobo
Created January 16, 2018 00:42
Show Gist options
  • Save Sstobo/fddb937331d1318edf31b9732220246a to your computer and use it in GitHub Desktop.
Save Sstobo/fddb937331d1318edf31b9732220246a to your computer and use it in GitHub Desktop.
[Reduce, map, filter, slice] #js
function toList(stockedList)
// Grocery store lab
const data = [
['apples', 73],
['pears', 12],
['oranges', 97],
['grapes', 387],
['grapes', 88],
['pears', 33],
['apples', 75],
['grapes', 23],
['oranges', 86],
['kiwis', 201]
];
// ######### REDUCE
// reduce can return anything, not just an array ect
// use reduce to reduce down a data type you dont like or want to change
// reduce iterates through the data array doing a function
function countFruit(data) {
// fruitlist is the 'accumulater' it takes each pass and builds it into a new array
return data.reduce((fruitList, currentItem) => {
// if "apple" is in the entire array (apple is list.currentitem(which will be whatever key this time through))
if (fruitList[currentItem[0]]) {
//if "apple" does exist, then att the currentitem[1] (number) to the key
fruitList[currentItem[0]] += currentItem[1]
} else {
fruitList[currentItem[0]] = currentItem[1]
}
return fruitList;
}, {});
}
const countedFruits = countFruit(data);
const objectCountedFruits = Object.entries(countedFruits)
// ####### map
// map iterates an array and creates a new array with the listed parameters
function stockUp(data, stockNumber){
const stockedUpList = { ...data };
Object.keys(stockedUpList).forEach(fruit => {
stockedUpList[fruit] += stockNumber;
});
return stockedUpList;
}
var stockedList = stockUp(countedFruits, 51);
function explain(data) {
let fruits = "";
Object.keys(data).forEach(fruit => {
fruits += `${data[fruit]} ${fruit}`;
});
return fruits.substring(0, fruits.length -2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment