Filter Duplicate Attributes in Array of Objects in Javascript

Catch duplicate attributes within an array of objects and retrieve unique elements. Array/object in question - const students = [ { name: "Rama", grade: 10 }, { name: "Kris", grade: 5 }, { name: "Pete", grade: 7 }, { name: "Mo", grade: 5 } ]; We want to get unique grades from the array. Option 1: Quickest way - use set Use a set to get unique values. We had a quick post on sets in Javascript just yesterday. const uniqueGradesSet = [...new Set(students.map(stu => stu["grade"]))]; console.log("uniqueGradesSet: ", uniqueGradesSet); // [ 10, 5, 7 ] Option 2: Use object + array combination Use an object with each iteration to check and filter duplicates. ...

Use Set in Javascript

Set was introduced in ES6 and is a collection of values without keys. It has one killer feature that you want to use - filtering duplicates owing to its feature of allowing only unique values. So.. set? People from other languages may be familiar with sets, maps and arrays.. and the confusion that comes with them. What is a set (map, or array)? Why should I use it? When should I use what? How is it different? Why am I alive? What is the purpose of life? As a Javascript developer, I was immune to that - use arrays for series of elements, objects for rest (aka keyed elements). ...

ES6 String Operations That Rock the World

There are many great improvements provided by ES6 (introduced in Y2015), but I think a couple of them are really cool. String includes includes checks whether a certain (sub) string exists in the provided string. Note that this operation is case sensitive. let str1 = "Neo rocks the world"; console.log("rocks? ", str1.includes("rocks")); // rocks? true console.log("is agent? ", str1.includes("agent")); // is agent? false Not quite complicated, but makes the language that much more friendly :) Earlier, we used a very complicated piece of code to achieve the same result. ...

Private Variables in Javascript Class

We define a class and its variables like so - class UserData { name = ""; type = ""; internalUserFlag = false; constructor({ name, type }) { this.name = name; this.type = type; } } const student1 = new UserData({ name: "Neo" }); console.log("student1: ", student1); // UserData { name: '', type: '', internalUserFlag: false } See quickly get started with Javascript classes if you want to know more. We can potentially extend the class and have multiple validation rules. We also like to keep variables like type and internalUserFlag private. These variables can be changed by extension classes, but not by external methods. ...

Extending Class in Javascript

Extend a class and create a sub class for easier maintainability. Sub class can make use of special super functions to extend the functionality of a class. Using sub classes you can build out a complex logic in steps rather than as one messy module. See how to start with a Javascript class and class prototypes if you are new to Javascript classes. Consider the example from our prototype discussion- User.prototype.users = []; class UserData { user = { name: "", type: "", }; setUser({ name, type }) { this.user.name = name; this.user.type = type; } addUser() { this.users.push(this.user); } } UserData.prototype.users = []; user1 = new UserData(); user1.setUser({ name: "Rama", type: "Teacher" }); user1.addUser(); console.log(user1.users); // [ { name: 'Rama', type: 'Teacher' } ] user2 = new UserData(); user2.setUser({ name: "Kris", type: "Student" }); user2.addUser(); console.log(user2.users); /* output [ { name: 'Rama', type: 'Teacher' }, { name: 'Kris', type: 'Student' } ] */ console.log(user1.users); // // [ { name: 'Rama', type: 'Teacher' } ] /* output [ { name: 'Rama', type: 'Teacher' }, { name: 'Kris', type: 'Student' } ] */ Our application works beautifully and allows us to define users. But, what if we want to store information specific to teachers and students? ...

Using Prototypes in Javascript Class

Prototypes enable us to define attributes and functions of a class that can be shared across its object instances. Let us look at how we could start using prototypes in our Javascript classes. See how to start with a Javascript class if you are new to Javascript classes. Class in Javascript is built internally using prototypes - in fact that was the way some of us were reaching OOP nirvana in Javascript back in the day. ESXX standards have changed all that and now we have classes and all the goodness therein. ...

How to Use Javascript Class?

Class in Javascript is syntactic sugar on top of prototypes. Class makes it easier to structure our code, and to read and maintain it. Let’s see a simple class. class QuizTracker { constructor() { this.right = 0; this.wrong = 0; this.points = 0; } addRight() { this.right++; this.points++; } addWrong() { this.wrong++; this.points -= 0.25; } getPoints() { return this.points; } } Class is the skeleton and provides the framework for an object. Object is an instance of the class and contains the structure supplied by class and the data. ...

Array Sort in Javascript

Arrays in Javascript can be sorted using a simple .sort command. But, don’t let that simplicity deceive you - it goes far more than that. let arr = [4, 2, 1, 7, 3]; console.log(arr.sort()); // [ 1, 2, 3, 4, 7 ] Sort can be used against full strings - let fruits = ["orange", "apple", "grapes"]; console.log("fruits.sort(): ", fruits.sort()); //[ 'apple', 'grapes', 'orange' ] It can use a custom function instead of the default sort logic. const fruits = [ { name: "orange", color: "orange" }, { name: "apple", color: "red" }, { name: "grapes", color: "green" }, ]; const fruitsSorted = fruits.sort((fruit1, fruit2) => { if (fruit1.color < fruit2.color) return -1; else if (fruit1.color > fruit2.color) return 1; else return 0; }); console.log("fruitsSorted: ", fruitsSorted); /* output fruitsSorted: [ { name: 'grapes', color: 'green' }, { name: 'orange', color: 'orange' }, { name: 'apple', color: 'red' } ] */ You can use any custom logic in the sort function, which makes it quite a powerful tool. However do remember - sort affects the original array. ...

Arrays in Javascript

Array is a collection of elements or objects, and is quite easy to use in Javascript. Here’s an example of array: const fruits = ["apple", "orange"]; You can print out the entire array.. const fruits = ["apple", "orange"]; console.log("fruits: ", fruits); //fruits: [ 'apple', 'orange' ] .. or access individual elements - const fruits = ["apple", "orange"]; So far we have seen You could also use an alternate (newer) notation that is easier to read - const fruits = ["apple", "orange"]; fruits.forEach((element) => { console.log("element", element); }); /* output element apple element orange */ The elements of an array can be of same or different data types. ...

Passing Arguments to a Javascript Function

You can pass one or more values to a function, but that has been made much easier and streamlined with the advent of ES2015 - 2018 standards. Let’s start with a simple function. function sum(x, y) { return x + y; } const summer = sum(3, 6); console.log(summer); // 9 If you follow the newer standards, you can rewrite the above function to - const diff = (x, y) => { return x - y; }; const differ = sum(6, 3); console.log(differ); // 3 If you change the order of arguments, the ‘sum’ function is not impacted, but ‘diff’ function is not impacted. I typically tend to use named variables to avoid this issue. ...