# Convert Array To Object JavaScript [4 Methods + Exercise]

As a front-end developer, working with data is essential to the job. However, it's not always a straightforward process - sometimes, the data we receive is not in the desired format. For instance, we may require an object to build our logic but receive an array instead. In such cases, we must convert the array into an object to facilitate our work.

In a previous article, we covered how to convert seconds to hours and minutes in Javascript. In this article, we'll be exploring various methods for converting arrays to objects in Javascript.

By mastering these techniques, you'll be able to handle data conversions with ease, and improve the efficiency and effectiveness of your front-end development projects.

## Turning Array into Object Using Freuquency Counter Pattern

The frequency pattern is a powerful technique for converting an array into an object. This method involves counting the frequency of each element that appear in an array, making it a valuable tool in a wide range of applications.

One of the most common use cases for the frequency pattern is determining the number of occurrences of each element in an array. This pattern can identify duplicates within an array easily.

### Method 01: Covert array to object Using for and forEach loop

```// with for loopconst arr = [6, 7, 2, 7, 4, 2]const frequencyCounter = {}
for (let val of arr) {  frequencyCounter[val] = (frequencyCounter[val] || 0) + 1}
// with forEach looparr.forEach((val) => (frequencyCounter[val] = (frequencyCounter[val] || 0) + 1))
// with traditional for loopfor (let i = 0; i < arr.length; i++) {  let letter = arr[i]  frequencyCounter[letter] ? (frequencyCounter[letter] += 1) : (frequencyCounter[letter] = 1)}
// frequencyCounter = {2: 2, 4: 1, 6: 1, 7: 2}```

### Method 02: Convert Array to Object Using Reduce Method

The `reduce` method is an incredibly useful higher order function in JavaScript, capable of solving many problems. It can simplify complex operations that involve iterating over an array and performing multiple operations on each element, making your code easier to read and maintain. We can achieve the same results as above.

```const frequencyCounter = arr.reduce((accu, curr) => {  accu[curr] = (accu[curr] || 0) + 1  return accu}, {})
console.log('frequencyCounter =>', frequencyCounter)
// frequencyCounter => { 2: 2, 4: 1, 6: 1, 7: 2 }```

Keys here represent an array element while values represent how many times an element appears. 2 appears 2 times and 4 appears 1 time and so on…

## Solve Problems by Changing Array into Object

As we discussed earlier, converting an array into an object can be useful for simplifying logic building in certain scenarios. One way to achieve this is through the frequency counter pattern, which involves counting the occurrences of each element in an array and creating an object with those counts as key-value pairs. In real-world challenges, this pattern can be applied to solve various problems.

One classic example of this is solving the Anagram problem, where the goal is determining whether two strings have the same characters in a different order. By applying the frequency counter pattern, we can create objects for both strings and compare them to see if they have the same counts as each character.

### What is Anagram

As per the Grammarly blog the Anagram are:

Anagrams are a form of wordplay in which the letters of a word or phrase are rearranged to create a new word or phrase. For example, if you take the letters from the words “a gentleman,” you can rearrange them to spell “elegant man.” By rearranging “Clint Eastwood,” you can spell “old west action.” “William Shakespeare” can be rearranged to spell “I’ll make a wise phrase.”

Let us solve it using what we have learned before in this article:

### Anagram Solution 01: With nested for loop

```function validAnagram(first, second) {  if (first.length !== second.length) {    return false  }
for (let i = 0; i < first.length; i++) {    let found = false
for (let j = 0; j < second.length; j++) {      if (first[i] === second[j]) {        found = true        second = second.slice(0, j) + second.slice(j + 1)        break      }    }
if (!found) {      return false    }  }
return true}
validAnagram('cat', 'act') // truevalidAnagram('cat', 'rat') // false```

### Big O

The time complexity of the `validAnagram` function is O(n^2)

### Anagram Solution 02: With frequency counter pattern

```const validAnagram = (first, second) => {  if (first.length !== second.length) {    return false  }
const lookup = {}
for (let val of first) {    lookup[val] = (lookup[val] || 0) + 1  }
for (let val of second) {    let letter = val
if (!lookup[letter]) {      return false    } else {      lookup[letter] -= 1    }  }
return true}
validAnagram('cat', 'act') // truevalidAnagram('cat', 'rat') // false```

### Big O

Now you can see instead of nested for loops we are using two loops but not nested, and made time complexity of the `validAnagram` function is O(n)

## Method 03: Convert array to object by making the Same key and values

Sometimes we may need the same keys and values to build the logic and get the desired result.

```const arr = [3, 7, 4, 9, 'bye', 'hello']const frequencyCounter = arr.reduce((accu, curr) => {  // accu[curr] = (accu[curr] || 0) + 1  accu[curr] = curr  return accu}, {})
console.log(frequencyCounter) // {3: 3, 4: 4, 7: 7, 9: 9, bye: 'bye', hello: 'hello'}```

### Note

For making the same keys and values, ensure there isn't any repeated element in an array because a Javascript object cannot have two keys with the same name.

## Method 04: Convert array to object by making Array index as key

Sometimes we want to make array index as keys while converting array into object.

```const arr = [3, 7, 4, 9, 'bye', 'hello']
const frequencyCounter = arr.reduce((accu, curr, i) => {  accu[i] = curr  return accu}, {})
console.log('frequencyCounter =>', frequencyCounter)
// frequencyCounter => {0: 3, 1: 7, 2: 4, 3: 9, 4: 'bye', 5: 'hello'}```

## Closing Notes

Whether working on a petite assignment or a grand application, you can enhance your code efficiency by converting arrays to objects. You can achieve remarkable outcomes with minimal exertion by utilizing JavaScript's built-in methods and syntax.