Skip to content

Instantly share code, notes, and snippets.

@ryan-hamblin
Created September 9, 2017 01:20
Show Gist options
  • Select an option

  • Save ryan-hamblin/04f7e53958d6ca0203cfd011d8383763 to your computer and use it in GitHub Desktop.

Select an option

Save ryan-hamblin/04f7e53958d6ca0203cfd011d8383763 to your computer and use it in GitHub Desktop.
reduce and flatten methods from ground up
const nums = ['1', '2', '3', '4', '5'];
const listOfPeeps = [
{
_id: '123512',
name: 'Ryan',
friends: ['Hermione', 'Ron', 'Harry', 'Draco'],
},
{
name: 'Donnie', _id: '32434',
friends: ['Batman', 'Superman', 'Thing', 'Human Torch', 'Cyborg'],
}
]
const customReduce = (arr, callBack, memo = arr.shift()) => {
for (let i = 0; i < arr.length; i++) {
memo = callBack(memo, arr[i]);
}
return memo;
};
const sum = customReduce(listOfPeeps, (object, item) => {
object[item._id] = item;
return object;
}, {});
console.log(sum);
const flatten = (arr) => {
let newArr = [];
for ( let i = 0; i < arr.length; i++ ) {
if (Array.isArray(arr[i])) {
newArr = newArr.concat(flatten(arr[i]));
} else {
newArr.push(arr[i]);
}
}
return newArr;
};
const nestedArr = [1, 2, 3, [4], [[5], [6, [7], [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[3, [[[[[[[[[[[[[[[[[[[[[[[[[[[234]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]];
console.log(flatten(nestedArr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment