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

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

console.log(arr4.flatMap((element) => element).flat(2)) ;

// expected output 
[1, 2, 3, 4, 5, 6, 7]
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 :: axios interceptors 
Javascript :: enzyme react 
Javascript :: arithmetic operators in javascript 
Javascript :: how to clear a function in javascript 
Javascript :: how to make a circle in p5js 
Javascript :: loading react 
Javascript :: working of timers in javascript 
Javascript :: async and await 
Javascript :: json-server localhost 
Javascript :: how to add two times in javascript 
Javascript :: react navbar material ui 
Javascript :: react: fow to use find(to get the id of a element 
Javascript :: find object from list 
Javascript :: print() in javascript 
Javascript :: Make Floating label TextInput in react native 
Javascript :: Ping discord 
Javascript :: navigator user media check if camera is availabe 
Javascript :: add/cart shopify api 
Javascript :: scroll up link 
Javascript :: dart json serializable 
Javascript :: javascript double question mark 
Javascript :: angular map 
Javascript :: find longest palindrome javascript algorithm 
Javascript :: adding methods to objects javascript 
Javascript :: modal slide from right 
Javascript :: typescript clear array 
Javascript :: json to yaml converter 
Javascript :: is checked jquery not working 
Javascript :: google scripts get document 
Javascript :: bootstrap carousel dynamic height jquery 
ADD CONTENT
Topic
Content
Source link
Name
4+3 =