Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
// 1. How to check if one array has all elements of another?
var importedEmails = ['john@doe.com', 'janet@doe.com'],
existingEmails = ['john@doe.com', 'janet@doe.com', 'fred@mercury.com'];
if(!_.difference(importedEmails, existingEmails).length) console.log('already imported')
// > already imported
// **********************************************************
// 2. How to find what elements are common to two arrays?
var tagsPost1 = ['ruby', 'rails', 'test'];
var tagsPost2 = ['test', 'rspec'];
_.intersection(tagsPost1, tagsPost2);
// > ["test"]
// **********************************************************
// 3. How to merge two Arrays without duplicating entries?
var followeds1 = [1, 2, 3],
followeds2 = [2, 4, 5];
_.union(followeds1, followeds2);
// > [1, 2, 3, 4, 5]
// **********************************************************
// 4. How to sort an Array of Hashes?
var data = [
{
name: 'Christophe',
location: 'Belgium'
},
{
name: 'John',
location: 'United States of America'
},
{
name: 'Piet',
location: 'Belgium'
},
{
name: 'François',
location: 'France'
}
];
_.sortBy(data, 'location');
// > [
// { location: "Belgium", name: "Christophe" },
// { location: "Belgium", name: "Piet" },
// { location: "France", name: "François" },
// { location: "United States of America", name: "John" }
// ]
// **********************************************************
// 5. How to keep objects in an Array that are unique with respect to one attribute?
var Product = function(id, categoryId){this.id = id; this.categoryId = categoryId; };
var products = [
new Product(1, 1),
new Product(2, 2),
new Product(3, 3),
new Product(4, 1),
new Product(5, 3),
new Product(6, 5),
];
products = _.uniq(products, 'categoryId');
// > [
// Product {categoryId: 1, id: 1},
// Product {categoryId: 2, id: 2},
// Product {categoryId: 3, id: 3},
// Product {categoryId: 5, id: 6},
// ]
// **********************************************************
//6. How to filter an Array with a string?
var books = [
'The Ruby Programming Language',
'Programming Ruby 1.9 & 2.0: The Pragmatic Programmers\' Guide (The Facets of Ruby)',
'Practical Object-Oriented Design in Ruby: An Agile Primer',
'Eloquent Ruby',
'Ruby on Rails Tutorial: Learn Web Development with Rails'
];
_.filter(books, function(book){ return book.match(/[Rr]ails/); });
//> ["Ruby on Rails Tutorial: Learn Web Development with Rails"]
// **********************************************************
//7. How to always get an Array?
var method = function (){
// ...
return [].concat(products);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment