Merge several arrays into a single array using an algorithm

Hey everyone, I'm facing a little problem here.

Basically, I have this object that contains 3 arrays...

items = {
    a: ['STRAWBERRY', 'PEANUT'],
    b: ['John', 'Doe', 'Scarface'],
    c: ['Circle', 'Square', 'Triangle', 'Rectangle'],
}

What I'm looking for is this specific output:

[
    'STRAWBERRY',
    'John',
    'Circle',
    'PEANUT',
    'Doe',
    'Square',
    'Scarface',
    'Triangle',
    'Rectangle'
]

IMPORTANT NOTE: THE OUTPUT NEEDS TO INTERLEAVE BETWEEN EACH VALUE OF THE ARRAYS INSIDE THE 'ITEMS' OBJECT

I've been trying to come up with an efficient way to achieve this without having to write a massive amount of code full of loops.

Does anyone know of a quick and optimized solution for this?

P.S.: I am open to using any available framework.

UPDATE Thanks to @evillive's response, I managed to adapt the approach into CoffeeScript

SOLUTION USING COFFEE SCRIPT

result = []
col = -1
loop
  col++
  run = false
  for k of Items
    Items[k][col] and (run = result.push(Items[k][col]))
  unless run
    break

console.log result

Answer №1

If you want to maintain the order, follow these steps: http://jsfiddle.net/o5k965ze/

var items = {
    a: ['STRAWBERRY', 'PEANUT'],
    b: ['John', 'Doe', 'Scarface'],
    c: ['Circle', 'Square', 'Triangle', 'Rectangle'],
};

function getLength (obj) {
    var length = 0;
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (obj[key].length > length) {
                length = obj[key].length;
            }
        }
    }
    return length;
}

function merge () {
    var newArray = [];
    var length = getLength(items);
    console.log(length);
    var index = 0;
    for ( ; index < length; index++) {
        for (var key in items) {
            if (items[key][index]) {
                newArray.push(items[key][index]);
            }
        }
    }
    console.log(newArray)
}

merge();

Using this method will ensure that you achieve the desired order, even when working with more than three arrays in the object.

Answer №2

In this solution, there is no need to specify a maximum length parameter for the lookup process.

var result = [];
while(Object.getOwnPropertyNames(items).length){
  for(var k in items){
    result.push(items[k].shift());
    if (items[k].length == 0) delete items[k];
  }
}

UPDATE: After realizing that using shift and delete impacts performance negatively, I have rewritten the code to optimize its speed significantly.

var result = [], col = -1, run;
do {
    col++; run = false;
    for(var k in items){
        items[k][col] && (run = result.push(items[k][col]))
    }
} while(run)

Answer №3

With the power of lodash, you can easily achieve this:

_.flattenDeep(_.values(list));

Answer №4

let Objects = {
  x: ['APPLE', 'BANANA'],
  y: ['Alice', 'Bob', 'Cindy'],
  z: ['Circle', 'Square', 'Triangle', 'Rectangle'],
};
let totalLength = 0;
let currentIndex = 0;
let finalOutput = [];

for (let key in Objects) {
  totalLength = Math.max(totalLength, Objects[key].length);
}

if (!totalLength) return finalOutput;

for (currentIndex; currentIndex < totalLength; currentIndex++) {
  for (let key in Objects) {
    let objectItem = Objects[key][currentIndex];
    objectItem && finalOutput.push(objectItem);
  }
}

return finalOutput;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display two radio buttons side by side in HTML?

Looking at my HTML form in this JSFiddle link, you'll see that when the PROCESS button is clicked, a form with two radio buttons appears. Currently, they are displayed vertically, with the female radio button appearing below the male radio button. I& ...

MongoDB aggregation function returning zero rather than the correct sum of numbers within an array

Here is the structure of my document: { "_id": "2023-04-08", "dailyNotes": [ { "therapyDiscipline": "PT", "individual": [ 60, 45, 30, 75, ...

Error message: The function pokemon.map does not exist

I'm new to learning react and I've been working on creating a react app using the pokemon API. However, I've encountered an error that says TypeError: pokemon.map is not a function. I'm unsure why .map is not recognized as a function in ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

Having trouble receiving values sent through AJAX POST requests to PHP

Can anyone help me figure out why my AJAX POST method is not sending the specific section of my URL string to my PHP file? I've checked everything and can't seem to find where the issue lies. When I var_dump the POST variable in my PHP file, it s ...

React: Struggling to render values within {} of a multidimensional object

I'm facing a challenge that I can't seem to overcome and haven't found a solution for. The values between curly braces are not displaying in the Content and Total components. I've double-checked the JSX rules, but it seems like I might ...

Vue project encounters disappeared DOM element

I'm currently developing a code typer, but I've encountered an issue where the element inexplicably turns into Null. Despite having some experience with Vue from my previous project on Django/Python at (live preview), I find myself struggling to ...

Implementing a Dropdown Menu Within a React Form

I am currently working on setting up a reservation system for rooms. I want to include 2-4 different room types and incorporate a dropdown menu instead of manual input. I am using the guidance provided here. I attempted to use <Form.Select...>, but i ...

Delay in displaying Promise API call in NextJS

Currently, I am encountering an issue while making calls to an API function that I have already set up and confirmed to work flawlessly in other projects. Interestingly, I have utilized the same backend API calling method in another project as well as with ...

Increase and decrease buttons using the 'keydown' event (ArrowUp and ArrowDown)

I'm seeking assistance with a school project. I currently have two buttons, one for incrementing and one for decrementing. There are four functions in total, two for clicking and two for using arrow keys. The clicking functionality works fine, but whe ...

Set a character to an array of characters within a structure that is nested inside an array of structures, which in turn is nested inside another array of structures within a final array

I have a unique challenge for a school project - simulating a hard disk. The structure of it involves nested arrays within structs as per the instructions given by my teacher. typedef struct block { unsigned char bytes_s[512]; } block; typedef struct ...

How can I locate a specific car brand within the car index I compiled earlier?

#include <cs50.h> #include <stdio.h> int main (void) { string indexcar[5]; // defining car brands in the index indexcar[0] = "Volvo"; indexcar[1] = "Mazada"; indexcar[2] = "Toyota"; indexcar[3] ...

Incorporating a rigged and animated asset into a preexisting scene using Three.js

Currently, I'm developing a browser app similar to Tamagotchi using three.js. However, I've hit a roadblock while trying to implement a hand that can pet the avatar when clicked. The Hand is a rigged Blender model with two animations: idle and p ...

Utilizing local storage, store and access user's preferred layout options through a click function

Exploring the realm of localstorage for the first time, I am considering its use to store a specific ID or CLASS from my css file. This stored information would then be utilized to render a selected layout (grid/list) in the user's browser upon their ...

The functionality of $watch is not functioning correctly within the Modal, despite implementing it with $scope.user={pwd1:''}

For the Plunker link referenced, please click here: http://plnkr.co/edit/0vOjw0?p=preview index.html <!DOCTYPE html> <html ng-app="app"> <head> <link rel="stylesheet" href="style.css"> ...

JavaScript: An object containing a unified handler for all method invocations

Let me explain further. Math.add(2, 2) //4 Math.multiply(4, 9) //36 Whenever a method in the Math object is invoked, it triggers a central processor that interprets the function name to determine its action. Can an object execute a default function when ...

Error: CSS and JavaScript files cannot be found

Currently working with an Orchard Asp.net MVC 3 Project. Upon examining the source code in the browser, I notice all the JS and CSS files being referenced/imported. However, clicking on the URL for certain JS files located in the MediaLibrary or Modules f ...

Error: The function Stripe.customers.cancel is not recognized in Stripe version 14.18.0

When executing Cypress tests that involve calling a cleanup function to remove users in Stripe, I encounter the following error: Body: { "status": 500, "message": "Error while cleaning the stripe test data", "error" ...

What is the method for creating a new array of objects in Typescript with no initial elements?

After retrieving a collection of data documents, I am iterating through them to form an object named 'Item'; each Item comprises keys for 'amount' and 'id'. My goal is to add each created Item object to an array called ' ...

Angular Resolution Verification

I'm currently working on making HTTP calls in Angular and I want to trigger a different service function if an error occurs. The problem is, no matter what the original service call function returns, the promise always ends up being "undefined". Here& ...