Posts

JavaScript: How to create an array of unique values using Set?

  How to create an array of unique values using Set? ES6 introduces Set, which returns unique values This article will go through how to remove duplicates and create an array of unique values ES6 Set. What is ES6 Set? The Set object is a data type that can store unique values without any particular order. We can pass in a parameter, and all of its elements will be added to the new Set. const result = new Set (parameter); How to create an array with unique values? For example, we want to create a new array with unique category values. const food = [ { name : "egg" , category : "breakfast" , }, { name : "burger" , category : "lunch" , }, { name : "steak" , category : "dinner" , }, { name : "chicken" , category : "lunch" , }, { name : "eggs" , category : "breakfast" , }, { name : "spaghetti" , category : ...

JavaScript: How to use Reduce method

  How to use reduce method The reduce() method executes a provided function for each array value (from left to right), resulting in a single output value. The syntax of the reduce() method: array.reduce( (accumulator, currentValue, index, array) => { ... }, initialValue) accumulator: the value returned from the previous iteration. It will be initialValue for the first iteration currentValue: the value of the current element index: the index of the current element (Optional) arr: array object (Optional) initialValue: A value to be passed to the function as the initial value (Optional) I. Sum numbers For example, we have an array of numbers, and we want to sum the numbers: // Using for loop const numbers = [1, 2 , 3 , 4 , 5 ]; let sum = 0 ; for (let i = 0 ; i < numbers.length; i++) { sum += numbers[i]; } console.log(sum); // 15 // Using reduce const numbers = [ 1 , 2 , 3 , 4 , 5 ] const sum = numbers.reduce( ( total, num ) => to...

JavaScript: Sort an array of objects { The sort() Method }

  How to sort an array of objects in JavaScript? In this article, we will see how to use JavaScript’s sort() method to sort arrays of numbers, strings, and objects. I. How to use the sort() method? The sort() method in JavaScript allows us to sort the elements of an array in ascending order. It sorts an array alphabetically. It changes the positions of the elements in the original array and returns the array itself. By default, the sort() function sorts values as strings. const months = [ "March" , "Jan" , "Feb" , "Dec" ]; months. sort (); console. log (months); // Output: [ "Dec" , "Feb" , "Jan" , "March" ] II. Sort array of numbers with sort() The sort() method converts the elements to strings and compares the strings to determine the order. Let’s take a look at an example. Example : const numbers = [40, 100 , 1 , 5 , 25 , 10 ]; numbers.sort(); console.log(numbers); // [1, 10 , 100 , 25 , ...