Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

flatmap javascript

var arr = [1, 2, 3, 4];

arr.flatMap(x => [x, x * 2]);
// is equivalent to
arr.reduce((acc, x) => acc.concat([x, x * 2]), []);
// [1, 2, 2, 4, 3, 6, 4, 8]
Comment

flatMap() method

const arr1 = [1, 2, 3, 4, 5];

const newArr1 = arr1.flatMap((x) => [x ** 2]);
console.log(newArr1); // [ 1, 2, 3, 4, 5 ]

// can also be done as
const intermediate = arr1.map((x) => [x ** 2]);
console.log(intermediate); // [ [ 1 ], [ 4 ], [ 9 ], [ 16 ], [ 25 ] ]

const newArr2 = intermediate.flat();
console.log(newArr2); // [ 1, 4, 9, 16, 25 ]

const numbers = [1, 2, 3, 4, 5, 6, 7];

// remove odd and split even element to two half elements
function func(n) {
  if (n % 2 === 0) {
    return [n / 2, n / 2];
  } else {
    return [];
  }
}
const newArr3 = numbers.flatMap(func);
console.log(newArr3); // [ 1, 1, 2, 2, 3, 3 ]
Comment

flatMap js

let arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// выравнивается только один уровень
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]
Comment

PREVIOUS NEXT
Code Example
Javascript :: change href javascript 
Javascript :: react native grid view 
Javascript :: js refresh 
Javascript :: how to convert string to camel case in javascript 
Javascript :: cambiar background image javascript 
Javascript :: react dynamic load script 
Javascript :: js find all max number indexes in array 
Javascript :: use location hook 
Javascript :: javasript array indexof 
Javascript :: moment is date equals 
Javascript :: user icon discord js 
Javascript :: using bootstrap with react 
Javascript :: radio javascript checked 
Javascript :: javascript sort object 
Javascript :: npm config proxy 
Javascript :: dynamic imports js 
Javascript :: findindex js 
Javascript :: http requests in vue 3 
Javascript :: print object keys 
Javascript :: discord js stats command 
Javascript :: fullcalendar angular add events 
Javascript :: eslint disable tag 
Javascript :: .env.development.local 
Javascript :: java script how to not allow soace 
Javascript :: prototype in javascript 
Javascript :: op in sequelize 
Javascript :: angular remove index of array 
Javascript :: mongoose express js require 
Javascript :: react-dom and babel cdn 
Javascript :: can we send raw json in get method in flutter 
ADD CONTENT
Topic
Content
Source link
Name
6+7 =