Merge various arrays into one array by consolidating the fields

first_list      = [1,2,3,4]
second_list     = ['a','b','c']

Is there a way to merge these two arrays into a single array with two fields?

for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  c = _ref[_i];
  mList.push({
    clients: c
  });
}
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
  c = _ref2[_i];
  mList.push({
    projects: c
  });
}

I attempted this method but it appears to only add objects to the existing array rather than creating an object item with two properties.

The current output is

Array [ Object, Object, Object, Object, Object, Object, Object ]
         |        |        |       |       |      |        |
      clients   clients clients clients project project  project

However, my desired outcome is :

Array [ Object, Object, Object, Object ]
         |        |        |       |      
      clients   clients clients clients
         +         +      +        +
      projects   projects projects  projects (null)

https://jsfiddle.net/3s8rasm6/

Answer №1

You have the option to iterate over both arrays in a single loop. By using the || operator, you can replace undefined values with null.

for (_j = 0, _len2 = _arr.length; _j < _len2; _j++) {
  list.push({
    customers: _arr[_j] || null,
    project: _arr2[_j] || null
  });
}

Answer №2

Combine both objects to work together. Visit this link for a demonstration

mList      = []
first_list = [1,2,3,4];
second_list = ['a','b','c'];

var c, _i, _len, _ref,_ref2;
_ref = first_list;
_ref2 = second_list;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  c = _ref[_i];
  mList.push({
    clients: _ref[_i],
    projects: _ref2[_i]
  });
}
console.log(mList);

Answer №3

VIEW DEMO

$(document).ready(function() {

  var prime_numbers = ['2', '3', '5', '7'];
  var even_numbers = ['4', '6', '8'];

  var alphabets = [];
  var animals = [];
  var merged_list = [];

  for (var i = 0; i < prime_numbers.length; i++) {
    alphabets.push({
      alphabet: prime_numbers[i]
    });
  }

  for (var i = 0; i < even_numbers.length; i++) {
    animals.push({
      animal: even_numbers[i]
    });
  }

  var max_length = Math.max(prime_numbers.length, even_numbers.length);

  for (var i = 0; i < max_length; i++) {
    merged_list.push($.extend(alphabets[i], animals[i]));
  }


  console.log(alphabets);
  console.log(animals);
  console.log(merged_list);
});

Answer №4

If you want to achieve this, you can utilize the lodash zipWith function:

let numList = [5, 10, 15, 20];
let strList = ['apple', 'banana', 'cherry'];

_.zipWith(numList, strList, (num, str) => {
    return {
        number: num || null,
        fruit: str || null
    }
})

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

If a dynamic route does not exist in NextJS, display a 404 error. Otherwise, show a loading spinner

I am facing an issue with the dynamic routes in my NextJS app, specifically /team/[id]. When the page loads, it queries the API to retrieve information based on the team ID. If the ID does not exist in the API, a 404 error is returned. However, I am strugg ...

Implementing the kendo-grid directive with a headerless row

Is it possible for the Kendo UI - Grid / AngularJS to display a grid without a header row? I am hoping to achieve this: https://i.sstatic.net/guYPf.jpg instead of this: https://i.sstatic.net/xlfgC.jpg If it is supported, what should the options in its ...

What is the best way to add a vanilla JavaScript keyup event listener to an Angular md-autocomplete input by utilizing the DOM id?

I am working with an angular md-autocomplete setup that looks like this: <md-autocomplete md-input-id="myid" ...> </md-autocomplete> My goal is to add an event listener like this: document.getElementById("myid") .addEventListener ...

Determining the total number of permutations of size N that match the original Array A after a function is applied to all subarrays of A

Given a permutation A of size N with distinct numbers from 0 to N-1, the MEX(A1, A2, , Ak) is the smallest non-negative integer that does not include in A1, A2, • • • , Ak. A permutation P of size N is considered identical to A if the MEX of every su ...

The status of the Ajax response is non-existent

On my local server (jsboss), I have a resource located at: Using the Mozilla RESTClient addon, when I access this URL, I receive the following response: Status Code: 200 OK Content-Length: 160 Content-Type: application/vnd.collection+json Alternatively, ...

Assistance with AJAX Promises and Deferred

I need a compact JavaScript library that handles Promises/Defers for handling multiple AJAX requests with MooTools. Most of the libraries I've come across use setTimeout functions in their examples, which doesn't demonstrate how to utilize the re ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

Ways to dynamically activate an anchor tag's click event using JavaScript?

I'm having trouble triggering an already written click event for an anchor tag using JavaScript. Can someone help me figure out how to do this? I have the following anchor tag: <a id="memberid">Data Member</a> <script> $("#memb ...

The data input from the HTML is not being correctly transferred to the modal

I am trying to transfer the reservation id from an HTML element to a modal window. When I click "cancel" next to a reservation, a modal should appear showing the reservation id. However, the modal pops up without displaying the reservation id. Can anyone h ...

Implementing setInterval() leads to the dynamic alteration of images

I've created Marquees using CSS animations and a countdown timer. The Marquees display 100 random images that move from left to right and right to left. However, when the countdown timer decreases, the images in the Marquee change but the scrolling co ...

Encountering an Unresolved Runtime Issue: TypeError arises when attempting to access properties of undefined (specifically 'call') while utilizing the Image component in next.js

I'm currently experimenting with the Image component offered by next.js. This Is My Basic Header Component import Image from 'next/image' import React from 'react' import myImage from '../assets/IMG-20221115-WA0001.jpg' ...

JavaScript ACTING UP -> CROSS-ORIGIN RESOURCE ACCESS ERROR

After extensive research and troubleshooting, it dawned on me that the issue was not with JavaScript itself. Instead, I was facing a cross origin resource exception, which occurred because the ajax request was unable to access my server script due to lac ...

Checking and contrasting dates within Javascript

Looking to compare two dates with different formats: a) Date1 - 01 Feb 2019 b) Date2 - 2/3/2017 It's important to account for invalid dates and ensure that Date1 is greater than Date2. function CompareAndValidateDates() { var Date1 ="01 Feb 20 ...

When utilizing Google Analytics in conjunction with Next.Js, encountering the error message "window.gtag is not

Encountering an error on page load with the message: window.gtag is not a function Using Next.js version 14.0.4. All existing solutions seem to hinder data collection, preventing the website from setting cookie consent correctly. I am uncertain about the ...

arranging data in a PHP array by column

I am attempting to organize the information in this data structure by a specific column. Here is how I have constructed it: $counter = 1; $entity_list = array(); foreach($result as $rec){ $entity_list[$counter]['student_first_name'] = $re ...

When you attempt to "add website to homescreen" on an iPhone, Ajax malfunctions

I have a unique website feature that utilizes ajax to dynamically load content when the user interacts with certain buttons. Everything functions smoothly up until a user tries to access the website through the "add to homescreen" option on mobile Safari a ...

Comparing strings in JavaScript arrays

I have developed a JavaScript function that compares two strings and calculates the number of similar characters using a specific logic: String 1 = “aaabc” | String 2 = “aakbc” ===> The function returns 2 String 1 = “88835” | String 2 = “ ...

Elevating the Components of an Array Similar to a Numeric Value

Currently, I am in the process of developing a Sudoku-solving program. In order to determine the solution for the puzzle, my program interprets 0s as vacant slots and generates an array that matches the total number of zeros present in the Sudoku puzzle. S ...

Using a loop to iterate through an object within a table cell and generate an unordered list

One of my tables contains a column where cells may or may not have values, with those values being in JSON format when they exist. Otherwise, the cells are empty (null). <table> <tbody> <tr> <td>Barley</td> <td>AK, ...

How come my dynamic source path doesn't function correctly unless I add an empty string at the end of it?

Recently, I encountered an issue while using Vue.js to dynamically create a source attribute using an object's properties. Here is the code snippet where I faced the problem: <img :src='"../assets/" + project.image.name + "." + project.image. ...