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. ...

Quickly Initiate Objects in Javascript

Initializing objects can be a pain. You may end up with multiple checks if you are trying to set a specific prop in the object path to a pre-defined value. For e.g. set color of a Kawasaki bike to ‘blue’. To do this we have to traverse through the object path from the root through color. This may be made more difficult if you may or may not get a partial array from an external function or a third party system. ...

Use Filter to Eliminate Duplicates in Javascript Array

Use array filters to remove duplicates in an array. We have seen how we could use sets or an intermediate object in a loop to eliminate duplicates within array.There always is a better way of doing things. Why not use filter to make the code more readable and not use set at the same time :) ? Consider this array - const nums = [1, 5, 0, 1, 2, 3]; The below code will create a unique array. const uniqueNums = nums.filter((num, index) => { return nums.indexOf(num) == index; }); console.log(uniqueNums); // [ 1, 5, 0, 2, 3 ] Why will this work? Well, because nums.indexOf(num) always returns the first index of a particular element. ...

Search using Array.find() in Javascript

Are you doing array search using the old school for-loops? Time to change, kid. Consider this array - const fruits = [ { name: "apple", color: "red" }, { name: "orange", color: "orange" }, { name: "pear", color: "green" } ]; To search for a specific value - console.log(fruits.find(val => val.name == "pear")); // { name: 'pear', color: 'green' } console.log(fruits.find(val => val.name == "grapes")); // undefined We use the Array.find method to retrieve search results. The argument for find takes a function which has the condition for find. In our case we pass a val which represents each item in the array, and compare the name prop to the given value. find returns the matched item or undefined. ...

GroupBy in Array using Reduce in Javascript

There is a really cool way to do group by in an array using reduce. The problem statement - you have an array of objects and need to create different arrays based on similar attributes. This is very similar to the SQL group by statement. Consider the example array - const fruits = [ (apple = { color: "red", shape: "round" }), (watermelon = { color: "green", shape: "square" }), (orange = { color: "orange", shape: "round" }), (pear = { color: "green", shape: "pear" }) ]; We have to group by color - all reds in one array, greens in next array and so forth. This can of course be done with a multiple, nested for loops. Or, you can push the array through a reduce statement that is fed an interesting function. ...

Manage Client Side Secrets in Javascript

How do you maintain secrets on the client-side? In one sentence - there are no secrets client-side. If you don’t want anyone to know about the secret, you should not send it to the client. The need for secrets Client may need user ids/passwords, API keys, API secrets etc. None of them can be trusted to the client. Your cookies can be read by a user or a client-program, your local storage is readable by users or third party sites, and your code is accessible by users. ...

Convert Strings to Numbers in Javascript

There are multiple ways to convert a given string to a number - so, which one to use and where? You would have also seen the more generic post on how to cast value from one type to another. But it may not be so apparent on which option to pick when you need to get numbers from a given string. The first approach is my preferred one. console.log(Number("hello")); // NaN console.log(Number("abc123")); // NaN console.log(Number("123abc")); // NaN console.log(Number("123")); // 123 console.log(Number("123.12")); // 123.12 The values returned by Number evaluate to true or false as expected. You could easily check for valid numbers and abandon operation if the string is not a number. ...

Default Function Arguments in Javascript

You can easily introduce default values for the arguments passed to a function. Consider this function - function sayHello(name) { return `hello ${name}`; } Calling this function without arguments will provide a not-so-pretty string. console.log(sayHello()); // hello undefined Even if someone had an existential crisis, I doubt they will like to be called ‘undefined’. So - let us change that. function sayHello(name) { name = name || "world"; return `hello ${name}`; } The ‘or’ statement will - retain name value if provided assign ‘world’ to name if name is falsy The results are more pleasing. ...

Convert String to Title Case in Javascript

We have a string.toLowerCase() and string.toUpperCase() in Javascript, but no out of the box function to convert to title case. Fear not if you are in that pickle - it is quite easy. function ConvertTitleCase(str) { const strArr = str.toLowerCase().split(" "); for (let i = 0; i < strArr.length; i++) { strArr[i] = strArr[i][0].toUpperCase() + strArr[i].slice(1); } return strArr.join(" "); } console.log(ConvertTitleCase("hello world")); // Hello World ConvertTitleCase takes one argument, which is a string. The string is split into distinct word array (split at ‘space’), and each word is then converted to initial cap. ...