Using objects in JavaScript algorithms with examples

Tomas Gonzalez
5 min readJan 11, 2021

--

Photo by Immo Wegmann on Unsplash

Using objects in JavaScript algorithms is pretty common. Specifically, objects in JS algos are great for collecting the frequency of values and comparing two or more inputs to each other. Some keywords and hints in algorithms to look out for that should scream to you to use an object, are: anagram, compare, frequency, or that there are multiple inputs in the function.

By the way, objects create key-value pairs. We’ll dive into why this is useful down below. I would also like to dive into how to find the keys and values of an object as well! Let’s get into it.

Objects in simplest terms

In its simplest form, an object is best explained as data structure in the form of key-value pairs and can saved to a variable. Here’s an example:

let personObject = {
name: "tomas",
age: 28,
gender: "male",
}
personObject=> {name:"tomas", age:28, gender:"male"}

Accessing the keys of an object

To access all keys of an object we simply call the Object.keys method on the object. This will give us an array of all the keys as strings in an object. Here’s a visual using the example above.

Object.keys(personObject)=> ["name", "age", "gender"]

Accessing the values of an object

We can do the same with all values. You can call Object.values on the object, except this time instead of strings we will receive the value in its original data type.

Object.values(personObject)=> ["tomas", 28, "male"]

We can also access the individual values by calling the object with a particular key in square brackets next to it.

personObject["name"]=> "tomas"

Entry pairs as arrays

We can access each of the key-value pairs as strings, which will be returned as arrays. We do this by calling Object.entries on the object.

Object.entries(personObject)=> ["name", "tomas"]
["age", 28]
["gender", "male"]

Practice Problems

Anagrams

Here is an anagram problem from LeetCode.

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

Valid Anagram: Problem 242

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

The hint is in the title of this problem and we’re comparing two inputs to each other. We have string s and string t. So this problem will need an object in its solution.

var isAnagram = function(s, t) {
// if the length is not the same in both strings; return false.
if (s.length !== t.length) return false;
————————————————————————————————————————————————————————————————————
/* In these next two blocks, we are creating an object from
string s.*/
// 1. We create an empty object with the variable "sObject"
// using object literal syntax
let sObject = {};
// 2. Next, we iterate through the string we want to create an
// object from and save it to "sObject"
for (let i = 0; i < s.length; i++) {
// saving each individual letter to variable letter
let letter = s[i];
//if the object contains the key, we're going to add 1 to
//its value - notice, we're accessing the individual key
if (sObject[letter]) {
sObject[letter] ++;
} //else we're going to initialize it
else {
sObject[letter] = 1;
}
}
————————————————————————————————————————————————————————————————————

// iterate through the t string, if the letter is in the object,
// decrement it. if the letter is not in the object, return
//false.
for (let i = 0; i < t.length; i++) {
let letter = t[i]
if (!sObject[t[i]]) {
return false;
} else {
sObject[t[i]]--;
}
}

return true;

};
// Note: allowing the object key to reach zero does not mean the key does not exist,
// it will exit the loop and return whatever you'd like in the end.
// But if the letter does not exist, this is not an anagram, and we want to return false.

In the above submission I’m showing how you would use this algorithm to compare one input to the other.

Frequency

A frequency problem from LeetCode.

—————————————————————————————————

Find Lucky Integer in an Array: Problem 1394

Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.

Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1.

Example 1:

Input: arr = [2,2,3,4]
Output: 2
Explanation: The only lucky number in the array is 2 because frequency[2] == 2.

Example 2:

Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them.

Example 3:

Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.

Example 4:

Input: arr = [5]
Output: -1

Example 5:

Input: arr = [7,7,7,7,7,7,7]
Output: 7

—————————————————————————————————

Here, our keyword is “frequency”. Although we are not comparing two inputs, we are comparing the values to one another. This is a perfect problem to use an object with.

var findLucky = function(arr) {
————————————————————————————————————————————————————————————————————
//creating an object here
// 1. We create an empty object with the variable "obj"
// using object literal syntax
let obj = {};

// 2. Next, we iterate through the string we want to create an
// object from and save it to obj

for (let i = 0; i < arr.length; i++) {
let num = arr[i]
if (obj[num]) {
obj[num] += 1;
} else {
obj[num] = 1;
}
}
————————————————————————————————————————————————————————————————————
// Below places the keys and the values in a variable and
creates a new empty array
let keys = Object.keys(obj);
let max = -1;

//Below if the key and value match && the key is greater than
//max, we set it to max
for (let i = 0; i < keys.length; i++) {
if (keys[i] == obj[keys[i]] && obj[keys[i]] > max) {
max = obj[keys[i]];
}
}
// we always return max at the end if
return max;
};
// 1. Create an object of the array with each value and its frequency
// 2. Check to see if the key matches the value
// 3. Initialize max at -1
// 4. If the key matches the value, save it to max
// 6. Return max
// Edge Case: if all keys match values, return the highest value
// if there are no matches return -1

Conclusion

Using objects for their key-value pairs allows for some quick searching methods when it comes to algorithms. They’re great when you know the keys so you can search for their values. Again, objects are also useful for comparing two sets of inputs of data. Also, they are great when looking for frequency of an input, character, or value.

I hope this blog helps when looking at frequency and anagram algorithms, and gives you some clues as to what to look for when striving for a solution.

--

--

Tomas Gonzalez
Tomas Gonzalez

Written by Tomas Gonzalez

Experienced Ruby on Rails and JavaScript based programmer with a background in journalism, creative content, and multimedia-marketing. I love coffee and food!

No responses yet