Skip to content

Instantly share code, notes, and snippets.

@kavitshah8
Last active September 11, 2015 06:27
Show Gist options
  • Save kavitshah8/51a89cde8b6097bea242 to your computer and use it in GitHub Desktop.
Save kavitshah8/51a89cde8b6097bea242 to your computer and use it in GitHub Desktop.
Most useful Array methods
var arr = ['javascript','css','html'];
function printSkill(element, index) {
console.log(element + ' is the ' + index + ' element in the array');
}
arr.forEach(printSkill);
var obj = { 'skill': 'javascript',
'user': 'Bill'
};
console.log(Object.keys(obj)); // ["skill", "user"]
var arr = ['10', '20', '30'];
function returnCube(ele) {
return ele * ele * ele;
}
var intArr = arr.map(returnCube); // [1000, 8000, 27000]
var arr = ['Bill', 'Chad'];
arr.push('Sue'); // 4
console.log(arr); // ["Bill", "Chad", "Sue"]
function returnSum(previousValue, currentValue) {
return previousValue + currentValue;
}
var sum = [0, 1, 2, 3, 4].reduce(returnSum);
console.log(sum); // 10
var arr = ['Bill', 'Chad', 'Sue'];
var shiftedArr = arr.shift(); // "Bill"
console.log(arr); // ["Chad", "Sue"]
// Given an endorsment array with objects containing skill and user keys
var endorsements = [
{ skill: 'javascript', user: 'Chad' },
{ skill: 'javascript', user: 'Bill' },
{ skill: 'javascript', user: 'Sue' },
{ skill: 'html', user: 'Sue HTML' },
{ skill: 'css', user: 'Sue CSS' },
{ skill: 'css', user: 'Bill CSS' }
];
// And we want to transform an given endorsment array with an array which is a collection of objects with key skill and users
// But user key is an array containing all the users with that particular skill
[
{ skill: 'javascript', user: [ 'Chad', 'Bill', 'Sue' ], count: 3 },
{ skill: 'css', user: [ 'Sue', 'Bill' ], count: 2 },
{ skill: 'html', user: [ 'Sue' ], count: 1 }
];
// Array methods: forEach(), map(), push()
// Object methods: Object.keys()
function transformData (endo) {
var tra = {};
endo.forEach(function(el) {
if (tra[el.skill]) {
tra[el.skill].push(el.user);
} else {
tra[el.skill] = [];
tra[el.skill].push(el.user);
}
});
var res = Object.keys(tra).map(function(key) {
var obj = {};
obj['skills'] = key;
obj['values'] = tra[key];
return obj;
});
console.log(res);
}
transformData(endorsements);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment