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, [2], 3, [4, 5], [6]];
const nextElements = elements.flat(); // [1, 2, 3, 4, 5, 6]
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], [7, [8]]]];
const result = elements.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8]
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, 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, 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 = Array(10).fill().map((a, i) => i);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const champions = [
{
name: "Darius",
level: 7,
},
{
name: "Katarina",
level: 12,
},
{
const champions = [
{
name: "Darius",
level: 7,
},
{
name: "Katarina",
level: 4,
},
{
const users = [
{
id: 1,
username: "supercoder",
},
{
id: 2,
username: "xXxSniperElitexXx",
},
{