Javascript basic algorithms

js algorithms

If you are working javascript then you need to understand these basic algorithm because these algorithm are very useful in your daily programming life.

Get uniq from array


// get uniq from array
const nums = [1, 2, 1, 1, 2, 1, 3, 4, 1 ];
const uniq = [...new Set(numbers)]; // => [ 1, 2, 3, 4 ]
const uniq2 = Array.from(new Set(numbers)); // => [ 1, 2, 3, 4 ]

Update an array object by property


// update an object in array by property
const initial = [ {id: 1, score: 1}, {id: 2, score: 2}, {id: 3, score: 4}];
const newVal = {id: 3, score: 3};
const updated = initial.map(x => x.id === newVal.id ? newVal : x);
console.log(updated); // => [ { id: 1, score: 1  }, { id: 2, score: 2  }, { id: 3, score: 3  }  ]

Remove an object from array by property


// remove object from array by property
const removeId = 3;
const without3 = initial.filter(x => x.id !== removeId);
console.log(without3); // => [ { id: 1, score: 1  }, { id: 2, score: 2  }  ]

Remove a key from an object


var a = {
foo: 'bar',
useful: 1,
useless: 2
}

const {useless, ...clean} = a;
console.log(clean); // => {foo: 'bar', useful: 1}

Merge an array of objects together


// merge an array of objects
const data = [ {a: 1}, {b: 2}, {c: 3} ];
const merged = data.reduce((res, obj) => ({...res, ...obj}), {});
console.log(merged); // => { a: 1, b: 2, c: 3  }

Flatten


// flatten an array of arrays
const arrayOfArray = [ [1, 2], [3, 4], [[5, 6]] ];
const flattened = arrayOfArray.reduce((res, a) => [...res, ...a], [] );
console.log(flattened); // => [1, 2, 3, 4, [5, 6]]

Subtract two Sets


// subtract two sets
const s1 = [ 1, 2, 3, 4, 5 ];
const s2 = [ 2, 4 ];
const subtracted = s1.filter(x => s2.indexOf(x) < 0);
console.log(subtracted);

You May Also Like

About the Author: Pankaj Bisht