Skip to content

Instantly share code, notes, and snippets.

@amolmt
Created February 27, 2021 18:25
Show Gist options
  • Select an option

  • Save amolmt/f70e97c72c8862774a22e2f945f5d976 to your computer and use it in GitHub Desktop.

Select an option

Save amolmt/f70e97c72c8862774a22e2f945f5d976 to your computer and use it in GitHub Desktop.

ES6 Array methods

let items = [
  { name: "iPhone", price: 1200 },
  { name: "OnePlus", price: 1000 },
  { name: "Samsung", price: 900 },
];

filter

let cheapestPhone = items.filter((item) => {
  return item.price < 1000;
});

console.log(cheapestPhone);

map

let brands = items.map((i) => {
  return i.name;
});

console.log(brands);

find

let resultByName = items.find((i) => {
  return i.name === "iPhone";
});

console.log(resultByName);

foreach

let justNames = [];

items.forEach((i) => justNames.push(i.name));

console.log(justNames);

some

let mostExp = items.some((i) => i.price > 1000);

console.log(mostExp);

every

let isLessThanT = items.every((i) => i.price <= 1200);
console.log(isLessThanT);

reduce

const totalPrice = items.reduce((curr, i) => {
  return i.price + curr;
}, 0);

console.log(totalPrice);

includes

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const includesOnePlus = numbers.includes(2);

console.log(includesOnePlus);

flatMap

const metrix = [
  [1, 2, 3],
  [4, 5, 6],
];
const flatMatrix = metrix.flat(1);
console.log(flatMatrix);
const deepMetrix = [[1, 1], [[[[4]]]]];
const flatDeepMetrix = deepMetrix.flat(Infinity);
const totalDeepMetrix = deepMetrix.flat(Infinity).reduce((a, v) => a + v, 0);
const nums = [1, 2, 3];
const strings = ["one", "two", "three"];

mapping using map()

const mapped = nums.map((n, i) => [strings[i], n]);
const flatMapped = nums.flatMap((n, i) => [strings[i], n]);
console.log(flatMapped);
console.log(mapped);

reduceRight

const rString = ["t", "s", "e", "b"];
console.log(rString.reduce((c, v) => c + v));
console.log(rString.reduce((c, v) => v + c));
console.log(rString.reduceRight((c, v) => c + v));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment