Skip to content

Latest commit

 

History

History
110 lines (90 loc) · 2.01 KB

22. map, filter, reduce.md

File metadata and controls

110 lines (90 loc) · 2.01 KB

JavaScript Array

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

map() Method

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

const square = numbers.map(item => item * item);
console.log(square);

Output

[ 1, 4, 9, 16, 25 ]

const names = ["James", "Marie", "Rosa"];

const fullNames = names.map(item => item + " Smith");
console.log(fullNames);

Output

[ 'James Smith', 'Marie Smith', 'Rosa Smith' ]

filter() Method

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

const result = number.filter(item => item < 3);
console.log(result);

Output

[1, 2]

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

const result = number.filter(item => item % 2 !== 0);
console.log(result);

Output

[1, 3, 5, 7]

reduce() Method

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

const reducer = (previousValue, currentValue) => previousValue + currentValue;

const result = numbers.reduce(reducer);
console.log(result);

Output

15

Programming Task

Create an array named greet with values 'hello', 'hi' and 'welcome'. const greet = ['hello', 'hi', 'welcome']; Use map() method to add a new string 'world' to each element of the array. Remember two words should be separated by a space. From the new array filter out the element that has more than 6 characters.

Solution:

const greet = ['hello', 'hi', 'welcome'];
const newValue = greet.map(item => item + ' world');
console.log(newValue);
const finalValue = newValue.filter(item => item.length > 6);
console.log(finalValue);

Output

["hello world", "hi world", "welcome world"]
["hello world", "hi world", "welcome world"]

Programiz Quiz

Q. What is the output of the program?

const numbers = [53, 22, 0, 10, 15];

const reducer = (previousValue, currentValue) => previousValue - currentValue;
let result = array.reduce(reducer);
console.log(result);
  1. Error
  2. 0
  3. 6
  4. 10

Answer: 3