12 Aug
12Aug


Sum all the values from an array

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


Min value from Array

let numbers = [5, 10, 15, 20];
let sum = numbers.reduce((x,y) => (x < y ? x : y));
console.log(sum);
output:
5


Max value from Array

let numbers = [5, 10, 15, 20];
let sum = numbers.reduce((x,y) => (x > y ? x : y));
console.log(sum);
output:
20


Reduce the length of an array using an Array length property

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']


Filter Unique Values

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]


Filter Array Data

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"]


Swap values with array destructuring

let x = 5;
let y = 10;
[x, y] = [y, x];
console.log(x, y);
output:
10 5


Initialize an array of size n and fill with default values

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]


Insert something in the middle of an array

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']


Shuffle elements of an Array

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]




Comments
* The email will not be published on the website.