Skip to content

Instantly share code, notes, and snippets.

@pebreo
Last active July 28, 2016 17:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pebreo/338411c66c13950b06226a37c1b88550 to your computer and use it in GitHub Desktop.
Save pebreo/338411c66c13950b06226a37c1b88550 to your computer and use it in GitHub Desktop.
Javascript Snippets

Using reduce without lodash

a = [1,2,3];
var y = a.reduce(function(sum, n){
	return sum + n;
}, 0);

console.log(y);
-> 6

Using reduce with lodash

var h = {'a':1, 'b':2, 'c':1}

var x = _.reduce(h, function(result, value, key){
	(result[value] || (result[value] = [])).push(key);
  return result;
}, {});

console.log(x);
 { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)

Use reduce without lodash 2

function createTodo(value){
  return {
    value: value,
  };
};
var _data = [
  createTodo("hello"),
  createTodo("world"),
  createTodo("foo"),
  createTodo("bar"),
  createTodo("hello")
];

var todosByValue = _data.reduce(function(hash, todo){
  (hash[todo.value] || (hash[todo.value] = [])).push(todo);
  return hash;
}, {});

console.log(todosByValue);
/*
output:
{
  hello: [{ value: 'hello' }, { value: 'hello' }],
  world: [{ value: 'world' }],
  ...
}*/

// reverse the process
var groupedByTodo = Object.keys(todosByValue).map(function(key){
  return todosByValue[key];
});

console.log(groupedByTodo);
/*
output:
[[{"value":"hello"},{"value":"hello"}],[{"value":"world"}],[{"value":"foo"}],[{"value":"bar"}]]
*/

Using map and filter using Babel (Javascript ES6)

var settings = {
    user_id            : 0,
    insight            : true,
    spike              : true,
    momentum           : true,
    all_tickers        : true,
    errorMsg           : false,
    port_tickers       : [],
    fav_tags           : [],
    sensitivity        : 'medium',
    email_notification : true
};

var filters = ['insight', 'spike', 'momentum'];

var x = filters.map(k => settings[k]).filter(v => v === true).length === 1;
console.log(x);
 false

Code Review Examples for Javascript lodash:

http://codereview.stackexchange.com/questions/129746/create-new-array-by-filter-origin-array http://codereview.stackexchange.com/questions/111704/group-similar-objects-into-array-of-arrays

lodash reference

// create a unique set of items from an arry of single variables
_.uniq()

example:
_.uniq([1,1,2,2,3,3])
-> [1,2,3]

// create a unique set of items from an array of objects
_.uniqBy([{k:1}, {k:1}, {k:2}], 'k')
> [{k:1}, {k:2}]

var obj = {x: 1};
var other = {x: 1};
_.isEqual(obj, other)
-> true

// deep comparison to make unique set of items
x = [{k: 1, x: 3}, {k:1, x: 3}]
y = _.uniqWith(x, _.isEqual);
-> [{k: 1, x: 3}]

// return true or false if an item is in an array
_.includes()

example:

_.includes([1,2,3], 'a');
-> false

// return an array that matches a criteria
_.filter()

// change an array by removing the matching criteria
_.remove()

example:

x = [1,2,3,4];
x = [1,2,3,4];
var y = _.remove(x, function(v) { return v % 2 == 0 });
x -> [1,3]
y -> [2,4]


// create an array 
_.map()


example:
x = [1,2,3,4];
y = _.map(x, function(v) { return v*2 });
-> [2,4,6,8]

// create a single value
_.reduce()

example:
x = [1,2,3]
_.reduce(x, function(sum, n) { 
    // sum is the return value from previous call of function()
    return sum + n;
}, 0);


// loop through a collection or array
_.each(collection, function(value, key){})

_.each(array, function(item){})
_.forEach() - same as each


for(i in arr) { 

  i - the index
  
  }
  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment