To get the sum we usually use a for loop and traverse through the list but Array reduce function can help us in achieving it in a single line
let numbers = [5, 10, 15, 20]; let sum = numbers.reduce((x,y) => return x+y); console.log(sum);
Output: 50
let numbers = [5, 10, 15, 20]; let sum = numbers.reduce((x,y) => (x < y ? x : y)); console.log(sum);
output: 5
let numbers = [5, 10, 15, 20]; let sum = numbers.reduce((x,y) => (x > y ? x : y)); console.log(sum);
output: 20
array.length() method can help in reducing the array length. It truncates the last value.
Let's skip my last name from my Intro line.
let myIntro = ["I", "am", "girish", "gupta"]; console.log(myIntro); myIntro.length = myIntro.length - 1; console.log(myIntro);
output: ['I', 'am', 'girish', 'gupta'] ['I', 'am', 'girish']
let values = [0, 0, 5, 10, 15, 15, 20, 20, 25]; let uniqueValues = [...new Set(values)]; console.log(uniqueValues);
output: [0, 5, 10, 15, 20, 25]
In below example the bucket elements are null and are ready to get filtered out.
let uncleanData = ["hi", "this is", null, null, "Girish"];
=
let cleanData
uncleanData
.filter(function(data) { return data; });console.log(cleanData);
Output:
["hi","this is", "Girish"]
let x = 5; let y = 10; [x, y] = [y, x]; console.log(x, y);
output: 10 5
let size = 10; let defaultValue = 50; let initializedArray = Array(size).fill(defaultValue); console.log(initializedArray);
output: [50, 50, 50, 50, 50, 50, 50, 50, 50, 50]
const weekDays = ['mon', 'tues', 'thur', 'fri', 'sat', 'sun']; const insertDay = 'wed'; const insertDayIndex = 2; // Solution - 1 const updatedDays = [...weekDays.slice(0, insertDayIndex), insertDay, ...weekDays.slice(insertDayIndex)]; console.log(updatedDays); // Solution - 2 weekDays.splice(insertDayIndex, 0, insertDay); console.log(weekDays);
output: ['mon', 'tues', 'wed', 'thur', 'fri', 'sat', 'sun'] ['mon', 'tues', 'wed', 'thur', 'fri', 'sat', 'sun']
let numbersequence = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const shuffledNumbers = numbersequence.sort(() => Math.random() - 0.5); console.log(shuffledNumbers);
output: [7, 0, 3, 8, 5, 2, 1, 9, 4, 6]