Sort Arrays on Multiple Attributes

You can quite easily sort arrays on multiple attributes using a simple Array.sort(). Consider this array - const students = [ { name: "Rama", grade: 10, class: 5 }, { name: "Kris", grade: 7, class: 1 }, { name: "Jan", grade: 8, class: 5 }, { name: "Kris", grade: 5, class: 7 } ]; Sorting based on grade is easy. const sorted = students.sort((a, b) => a.class - b.class); console.log("sorted: ", sorted); /* output [ { name: 'Kris', grade: 7, class: 1 }, { name: 'Rama', grade: 10, class: 5 }, { name: 'Jan', grade: 8, class: 5 }, { name: 'Kris', grade: 5, class: 7 } ] */ If we add a further or condition in the sort criteria, Javascript can sort on both attributes. ...

Merge Arrays / Objects using Spread Operator

You can use the ... operator to perform black magic in Javascript. Consider the below example - const arrNums = [1, 2, 3]; const arrMoreNums = [4, 5, 6]; const allNums = [...arrNums, ...arrMoreNums]; console.log("allNums: ", allNums); // [ 1, 2, 3, 4, 5, 6 ] This is much much more efficient than writing code to go through two loops and merging them. The same is true for objects. const objNums = { a: 1, b: 2, c: 3 }; const objMoreNums = { x: 98, y: 99, z: 100 }; const objAllNums = { ...objNums, ...objMoreNums }; console.log("objAllNums: ", objAllNums); //{ a: 1, b: 2, c: 3, x: 98, y: 99, z: 100 } And no - you cannot convert types through spread. That is dark black magic and is not possible at this time. ...

Similar Methods Across Objects in Javascript

How can you use methods of one object type against another object type? How can you use the feature to your advantage? In another post, we had discussed how Javascript can use call to invoke methods of a function in a different context. We can use this feature to our advantage. Consider a string and array - let alpha = ["a", "b", "c"]; const alphaCap = String.prototype.toUpperCase.call(alpha); console.log("alphaCap: ", alphaCap.split(",")); // [ 'A', 'B', 'C' ] Without explicitly converting alpha array, we can apply string manipulation methods directly on array. Did you note that the result was a string, and we had to convert back into an array. Yes, that happened. ...

Check if objects are empty in Javascript

Check if a given object is empty without considering any custom props defined by prototype. Consider this sample object - const earth = {}; Use Object.entries() or equivalent Object.entries gives us a short way to access entries in an array form. We could just check whether entries are empty to decide whether the parent object is empty. const earth = {}; const isEmpty = !Object.entries(earth).length; console.log(isEmpty); // true The above logic is unaffected even if the object has defined properties. ...

Method of a Function in Javascript

A function can have its own methods - strange but true. Why? Because everything in Javascript is an object and object can have methods. Consider - function getSum(x, y) { return x + y; } console.log(getSum(1, 2)); //3 console.log(getSum.call(this, 1, 2)); //3 The first call to getSum is as expected. The second call uses a method called call and passes this as the argument along with the two numbers. This is equivalent to the first call. Or, use call’s friend apply - ...

Create Chainable Interfaces in Javascript

Chainable interfaces make your code readable and, arguably, your life more enjoyable. Chainable interfaces are those series of methods that you see chained to an object. You can use them for objects where “relevant”. Commonly used functions It is common to see methods chained to one another. The chaining works from left to right, with results from the left-side of the function passed to the right in sequence. const message = "hello world"; const newMsg = message .replace("h", "y") .toUpperCase() .substr(0, 6); console.log("message: ", newMsg); // YELLO Custom Objects One of the ways of demonstrating chainable interfaces for our own objects is by defining a function, and defining props and prototypes for the function. ...

Deleting Object Properties The Right Way in Javascript

Do not set properties to null or empty, always use delete. Consider - const earth = { name: "earth", position: 3, aweIndex: 42 }; console.log(earth); // { name: 'earth', position: 3, aweIndex: 42 } If you set any property to null - earth["aweIndex"] = undefined; console.log(earth); // { name: 'earth', position: 3, aweIndex: undefined } You can expect similar results if you set the prop to null. If you really want to delete the object, do a delete prop. delete earth["aweIndex"]; console.log(earth); // { name: 'earth', position: 3 } And before you ask - yes, this is covered when we were discussing (almost) everything about object and props in Javascript. ...

Object vs. Prototype Properties in Javascript

Check if a given object has a specified property. You can either use non-enumerable props or hasOwnProperty. Consider the below code - Object.prototype.awesomeness = 42; const earth = {}; console.log(earth["awesomeness"]); // 42 We have defined a prototype that gets attached to any object. Therefore the prop defined by prototype is attached to the object as well. What if you want to check all props in earth? for (prop in earth) { console.log(prop, ":", earth[prop]); // 42 } Even when the object is empty, the awesomeness prop rears it beautiful head. ...

Quickly Check if Array Elements Satisfy Given Criteria in Javascript

Use Array.some() and Array.every() to check whether an array has elements that satisfy the given criteria. Consider the below array - const nums = [3, 5, 6, 1, 2]; You can check whether the elements satisfy a specified criteria with below code - console.log(nums.some((val, index) => val > 3)); // true console.log(nums.some((val, index) => val > 10)); // false You can do the same for objects in the array. const fruits = [(apple = { color: "red" }), (orange = { color: "orange" })]; console.log(fruits.some((val, index) => val.color == "red")); // true console.log(fruits.some((val, index) => val.color == "blue")); // false In a similar vein, you can check whether every element in the array satisfies a given criteria. ...

Convert JSON to Array in Javascript

Often my server DB functions return the data in JSON format with all fields and values thrown in. const alphaNum = { a: 1, b: 2, c: 3, d: 4, e: 5 }; When we use charts (or even tables), this needs to be converted to an array of arrays. Most of the iterative functions work well with arrays and not objects. We would want to convert the object into [['a', 1], ['b', 2]...]. Use Object.keys We can convert JSON to array by using a map function on Object.keys. ...