Skip to content

Instantly share code, notes, and snippets.

View ancyrweb's full-sized avatar
🏠
Working from home

Anthony Cyrille ancyrweb

🏠
Working from home
View GitHub Profile
const elements = [1, 6, 4, 5, 2, 3];
const byOrderAsc = (a, b) => a - b;
const nextElements = elements.slice().sort(byOrderAsc); // [1, 2, 3, 4, 5, 6]
const elements = [1, 2, 4, 5];
const indexToInsert = 2; // we will append the element at index 2
const elementToInsert = 3; // we will insert the number "3"
const nextElements = elements.reduce((previousValue, currentValue, index) => {
previousValue.push(currentValue); // 😱
if (index === indexToInsert) {
previousValue.push(elementToInsert); // 😱😱
}
return previousValue;
const elements = [1, 2, 4, 5];
const indexToInsert = 2; // we will append the element at index 2
const elementToInsert = 3; // we will insert the number "3"
const nextElements = [
...elements.slice(0, indexToInsert),
elementToInsert,
...elements.slice(indexToInsert),
]; // [1, 2, 3, 4, 5]
const elements = [1, [2, [3, 4, [5], 6], [7, [8]]]];
const result = elements.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8]
function flatten(array) {
return array.reduce((previousValue, currentValue) => {
if (Array.isArray(currentValue)) {
// current value is an array, merge values and return the result
return [...previousValue, ...currentValue];
}
// current value is not an array, just add it to the end of the accumulation
return [...previousValue, currentValue];
}, []);
const elements = [1, [2], 3, [4, 5], [6]];
const nextElements = elements.flat(); // [1, 2, 3, 4, 5, 6]
const users = [
{
name: "Jane",
balance: 100,
},
{
name: "John",
balance: 75,
},
{
const elements = [1, 2, 3, 4, 5];
const sum = (a, b) => a + b;
const nextElements = elements.reduce(sum, 0); // 15
const elements = [1, 2, 3, 4, 5];
const nextElements = elements.reduce(
(previousValue, currentValue) => previousValue + currentValue,
0
); // 15
const elements = [1, 2, 3, 1, 4, 5, 2, 6, 6];
const isUnique = (value, index, array) => array.indexOf(value) === index;
const nextElements = elements.filter(isUnique); // [1, 2, 3, 4, 5, 6]