Split array entries to form object in JavaScript


The problem statement is saying that we have to find a solution for a given array and split it to form an object with a key-value pair in javascript.

Understand the problem

In simple terms we have to convert a given array into an object. There are several methods present in javascript to convert an array into an object. We will use and code each of them one by one.

Using reduce() and split() methods

In this method we will use reduce and split functions of javascript.

Algorithm

The algorithm here discusses the problem statement to be solved for arbitrary numbers of arrays present in an array itself .

Step 1 : Declare an array with the name data and add some values in it.

Step 2 : Declare a variable with name result to store the result.

Step 3: To split the array entries we will reduce() method to iterate over the array.

Step 4: Now split every entry into two parts using the - delimiter. So, we can group the entries by the first part of the split entry and count the number of occurrences for each single pair of company and model.

Step 5: In this step increment the count to 1 if there is a duplicate entry.

Step 6: Return the result after converting it to object and print it.

Example

// Define data in the form of array 
const data = [
   "Honda−Amaze",
   "Honda−Jazz",
   "Honda−Jazz",
   "Honda−SUV",
   "Volkswagen−Voyage",
   "Volkswagen−Atlas",
   "Volkswagen−Atlas",
   "Volkswagen−Voyage",
   "Fiat−Punto",
   "Fiat−Panda",
   "Fiat−Strada",
   "Fiat−Punto",
   "Fiat−Uno",
   "Ford−Fiesta",
   "Fiat−Uno",
];

//split data using reduce and split functions
const result = data.reduce((a, b) => {
  const [Company, model] = b.split("−");
  const key = Company + "−" + model;
  a[key] = a[key] || { Company, model, count: 0 };

  // Increment the count
  a[key].count++;

  return a; //
}, {});

const output = Object.values(result);
console.log("The data in Key - Value pair with count")
console.log(output);

Output

The data in Key - Value pair with count
[
  { Company: 'Honda', model: 'Amaze', count: 1 },
  { Company: 'Honda', model: 'Jazz', count: 2 },
  { Company: 'Honda', model: 'SUV', count: 1 },
  { Company: 'Volkswagen', model: 'Voyage', count: 2 },
  { Company: 'Volkswagen', model: 'Atlas', count: 2 },
  { Company: 'Fiat', model: 'Punto', count: 2 },
  { Company: 'Fiat', model: 'Panda', count: 1 },
  { Company: 'Fiat', model: 'Strada', count: 1 },
  { Company: 'Fiat', model: 'Uno', count: 2 },
  { Company: 'Ford', model: 'Fiesta', count: 1 }
]

Using the Object.assign() method

Object.assign() method is introduced in javascript ES6. The working mechanism of this function is to copy the values of all countable own elements from one or more input objects to an output object. The output object is the first argument and is also used as the return value. In the following sample of code we can demonstrates the usage of Object.assign() method to convert an array into an object:

Algorithm - for Object.assign()

Step 1: Declare an array with the name cars.

Step 2: Create another variable named objOutput and use the Object.assign method in it and pass the array cars.

Step 3: Return the output in object form.

Code for Object.assign()

Example

const cars = ["Honda", "Volkswagen","Fiat", "Suzuki"];

//using Object.assign to convert in object
const objOutput = Object.assign({}, cars)

console.log("Output using Object.assign() method")
console.log(objOutput)

Output

Output using Object.assign() method
{ '0': 'Honda', '1': 'Volkswagen', '2': 'Fiat', '3': 'Suzuki' }

Using the spread syntax (...)

To convert the array into an object we can use the spread operator. It will convert and start with 0 index.

Algorithm - for spread operator

Step 1: Define an array with the name cars.

Step 2: Create another variable named objOutput and use spread (...) operator in it and pass the array cars.

Step 3: Return the output in object form.

Code for the spread operator

Example

const cars = ["Honda", "Volkswagen","Fiat", "Suzuki"];

//using spread operator to convert in object
const objOutput = {...cars} 

console.log("Output using spread operator")
console.log(objOutput)

Output

Output using spread operator
{ '0': 'Honda', '1': 'Volkswagen', '2': 'Fiat', '3': 'Suzuki' }

Using the Array.forEach()

With the help of the forEach method we can change an array into an object with 0th index.

Algorithm - for forEach() method

Step 1: Initiate an array by giving the name cars.

Step 2: Create an empty object named objOutput and use forEach() method in it and pass the array cars.

Step 3: Return the output in object form.

Code for forEach() method

Example

// define an array
const cars = ["Honda", "Volkswagen","Fiat", "Suzuki"];

//using forEach method to convert in object
const objOutput = {}

cars.forEach((element, i) => {
  objOutput[i] = element
})

console.log("Output using forEach method")
console.log(objOutput)

Output

Output using forEach method
{ '0': 'Honda', '1': 'Volkswagen', '2': 'Fiat', '3': 'Suzuki' }

Time and Space Complexity

As we have optimized the algorithm using reduce, Object, split, spread operator, Object.assign and forEach methods powerful concepts of javascript. It gives the time complexity of algorithm O(n), where n is the number of elements in the array called data. Because we have iterated over the array only once using the reduce() function. The space complexity is also O(n), since we create a new object for each unique pair of company and model, and the size of this object depends on the number of unique pairs in the input array.

Conclusion

This is how we can solve the stated problem by thinking logically and efficiently in the context of coding. As we have hands-on experience of reduce, split and Object powerful methods of javascript. And we have come to a conclusion that this algorithm will take O(n) time to complete the execution and O(n) space to save in the memory.

Updated on: 18-Aug-2023

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements