Lodash methods with practical examples
Illarion Khapyorskiy @illarionvk
Lodash methods with practical examples
Illarion Khapyorskiy @illarionvk
1 _.map([1, 2, 3], function(value) {
2 return value * 3;
3 });
4 // → [3, 6, 9]1 _.map('Hello World', function(x) {
2 return x.charCodeAt(0);
3 });
4 // → [ 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 ]1 _.reduce(
2 [1, 2, 3],
3 function(accumulator, value) {
4 return accumulator + value;
5 },
6 0
7 );
8 // → 61 _.reduce(
2 [1, 2, 3],
3 function(accumulator, value) {
4 accumulator[value] = true;
5 return accumulator;
6 },
7 {}
8 );
9 // → {1: true, 2: true, 3: true}1 _.filter([1, 2, 3, 4, 5, 6], function(value) {
2 return value > 3;
3 });
4 // → [4, 5, 6]1 _.reject([1, 2, 3, 4, 5, 6], function(value) {
2 return value > 3;
3 });
4 // → [1, 2, 3]1 _.chain([1, 2, 3, 4, 5, 6])
2 .filter(function(value) { return value > 3; }) // → [4, 5, 6]
3 .map(function(value) { return value * 5; }) // → [20, 25, 30]
4 .reduce(function(accumulator, value) {
5 return accumulator + value;
6 }, 0)
7 .value();
8 // → 75https://github.com/illarionvk/warsawjs-find-duplicates-in-array
1 _.chain([1, 2, 3, 4, 5, 6, 7, 3, 4, 4])
2 .groupBy(function(item) {
3 return item;
4 })
5 .pairs()
6 .filter(function(pair) {
7 return _.last(pair).length > 1;
8 })
9 .map(function(pair) {
10 return _.first(pair);
11 })
12 .value();
13 // → ["3","4"] 1 _.chain([1, 2, 3, 4, 5, 6, 7, 3, 4, 4])
2 .groupBy(function(item) {})
3 // → {"1":[1],"2":[2],"3":[3,3],"4":[4,4,4],"5":[5],"6":[6],"7":[7]}
4 .pairs()
5 // → [ ["1",[1]],["2",[2]],["3",[3,3]],
6 // ["4",[4,4,4]],["5",[5]],["6",[6]],["7",[7]] ]
7 .filter(function(pair) {})
8 // → [["3",[3,3]],["4",[4,4,4]]]
9 .map(function(pair) {})
10 .value();
11 // → ["3","4"] 1 var item = {"a":{"b":{"c":3}}};
2
3 _.get(item, 'a.b.c', 3);
4 // → 3
5
6 _.set(item, 'a.b.c', 5);
7 // → {"a":{"b":{"c":5}}}
8
9 _.has(item, 'a.b.c.d');
10 // → false1 // avoid costly calculations while the window size is in flux
2 jQuery(window).on('resize', _.debounce(calculateLayout, 150));1 // avoid excessively updating the position while scrolling
2 jQuery(window).on('scroll', _.throttle(updatePosition, 100));1 _.startCase('+Hello++world+');
2 // → Hello World1 _.camelCase('+Hello++world+');
2 // → helloWorld1 _.snakeCase('+Hello++world+');
2 // → hello_world