Combining two objects of varying sizes using the lodash method

Is there a way to combine two arrays of objects in a specific pattern like this?

var a = [{id: 1, val: 1},{id: 2, val: 2},{id: 3, val: 3},{id: 4, val: 4},{id: 5, val: 5}];
var b = [{id: 21, val: 21},{id: 22, val: 22},{id: 23, val: 23}]

// The desired result is:
c = [
  {id:1, val: 1},
  {id:21, val: 21},
  {id:2, val: 2},
  {id:22, val: 22},
  {id:3, val: 3},
  {id:23, val: 23},
  {id:4, val: 4},
  {id:5, val: 5}
]

I could write the code myself, but I'm curious if lodash has a built-in method for this.

Answer №1

To start, you can combine the arrays, then flatten the outcome before using eliminating any missing elements (the zip method introduces them as undefined):

var result = _.compact(_.flatten(_.zip(array1, array2)))

You could also chain these operations:

var result = _(array1)
    .zip(array2)
    .flatten()
    .compact()
    .value()

var array1 = [{id: 1, val: 1},{id: 2, val: 2},{id: 3, val: 3},{id: 4, val: 4},{id: 5, val: 5}];
var array2 = [{id: 21, val: 21},{id: 22, val: 22},{id: 23, val: 23}]

var result = _(array1)
    .zip(array2)
    .flatten()
    .compact()
    .value()
    
document.getElementById('output').textContent = JSON.stringify(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

<pre id="output"></pre>

Answer №2

var arrayOne = [{id: 1, val: 1},{id: 2, val: 2},{id: 3, val: 3},{id: 4, val: 4},{id: 5, val: 5}];
var arrayTwo = [{id: 21, val: 21},{id: 22, val: 22},{id: 23, val: 23}];

// Combining two arrays by iterating through the largest one and interleaving elements
var resultArray = _.reduce(arrayOne.length < arrayTwo.length? arrayTwo: arrayOne, function(result, _, index) {
  if(index < arrayOne.length) result.push(arrayOne[index]); // Add element from arrayOne if available
  if(index < arrayTwo.length) result.push(arrayTwo[index]); // Add element from arrayTwo if available
  return result;
}, []);

console.log(resultArray);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Answer №3

To achieve this in vanilla JavaScript, you can create a function that loops through both arrays up to the minimum length, combines the values, and then appends the remaining elements at the end.

function mergeArrays(array1, array2) {
    var mergedArray = [],
        i = 0,
        minLength = Math.min(array1.length, array2.length);
    while (i < minLength) {
        mergedArray.push(array1[i], array2[i]);
        i++;
    }
    return mergedArray.concat(array1.slice(i), array2.slice(i));
}

var arr1 = [{ id: 1, val: 1 }, { id: 2, val: 2 }, { id: 3, val: 3 }, { id: 4, val: 4 }, { id: 5, val: 5 }],
    arr2 = [{ id: 21, val: 21 }, { id: 22, val: 22 }, { id: 23, val: 23 }];

console.log(mergeArrays(arr1, arr2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

JavaScript ES5 solution utilizing Math.max() (to determine the larger array size) and Array.prototype.push() functions:

var arr1 = [{id: 1, val: 1},{id: 2, val: 2},{id: 3, val: 3},{id: 4, val: 4},{id: 5, val: 5}],
    arr2 = [{id: 21, val: 21},{id: 22, val: 22},{id: 23, val: 23}],
    maxLength = Math.max(arr1.length, arr2.length), lenArr1 = arr1.length, lenArr2 = arr2.length,
    maxArray = lenArr1 > lenArr2 ? arr1 : arr2;
    resultArr = [];

for (var j = 0; j < maxLength; j++) {
    (j < lenArr1 && j < lenArr2) ? resultArr.push(arr1[j], arr2[j]) : resultArr.push(maxArray[j]);
}

console.log(resultArr);

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

Utilizing a string as a variable in AngularJS: a step-by-step guide

Can anyone help me figure out how to utilize a string as a variable within the scope in my code? Here's what I have: In my HTML (where type1 can be type2, type3, and more): <div style="color:red;font-size:11px;">{{ error.type1 }}</ ...

ng-repeat did not properly listen for changes in the radio box selection

Feeling a bit confused here. I'm trying to call a function on change and pass the obj to it. From what I understand, since it's bound to the selected obj, I should be able to just use ng-model. However, in this situation, nothing happens when I s ...

Why is my AngularJS controller receiving 'undefined' data from my service request?

Question: I am facing an issue where my service is successfully retrieving the necessary data, but my controller is not able to access it. What could be causing this problem? Service: Below is the code that my controller calls. // search.service.js (func ...

Tips for personalizing the color scheme of Material UI Stepper Step?

I need help customizing the disabled Step color for Material UI Steppers. The default colors are Blue for enabled steps and Grey for disabled steps, but I want to change it to a different color as shown in this example: https://i.stack.imgur.com/HGGxp.png ...

The success callback is not triggered when making a JSONP request

I have a specific URL that returns JSON data when accessed through a browser or REST client. However, I am having trouble making the request using jQuery in my express server running over HTTPS. Despite receiving a successful response in the network debug ...

The jQuery fadeOut function modifies or erases the window hash

While troubleshooting my website, I discovered the following: /* SOME my-web.com/index/#hash HERE... */ me.slides.eq(me.curID).fadeOut(me.options.fade.interval, me.options.fade.easing, function(){ /* HERE HASH IS CLEARED: my-web.com/index/# * ...

Redirecting with React Router outside of a route component

I am using React Router in my application to manage the routing functionalities. However, I have encountered an issue where I need to redirect the user from the Header component, which is not nested inside the Router component. As a result, I am unable t ...

What is the best way to loop back to the beginning of an array after reaching the last element in JavaScript?

I have an array in JavaScript containing music notes: const musicNotes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B&apos ...

Angular 2: Troubleshooting Issues with Observable Data Display

Looking to implement a RESTful call with Angular 2 that constantly updates whenever there are changes in the API. In my service, I've included an Observable to fetch data from the API: getData(): Observable<any[]> { return this.http.get(url) ...

Understanding Vue.js - encountering the error message "property or method is not defined"

Recently, I've come across an issue that seems to be common among many people, but for some reason, I am unable to find a solution despite looking at similar questions. The problem arises when I use a v-for in a Vue Component and the array value cons ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

Submitting jQuery Ajax forms multiple times using the POST method

After trying various solutions for this issue, none seem to effectively address my problem. Here are some examples: $("form#sending-notice-form").unbind('submit').bind('submit', function (e) { e.preventDefault(); .. }); While ...

Updating serialized $_POST array with new key/value pair using jQuery AJAX

Is there a way to insert additional values into a serialized $_POST array before sending an AJAX request using jQuery? Here's the situation: $('#ajax-preview').on('click', function(e) { e.preventDefault(); var formData = ...

Invalid JSON data was returned by the Ajax callback

I attempted the code below, but unfortunately, the JSON output is considered invalid. MY PHP $myArray = array(); $myArray["item"]["content"] = $item_content; echo json_encode($myArray); MY JavaScript .. dataType: "JSON", success: function(data){ consol ...

What happens when the next button is clicked without any items selected?

I am working on a dynamic HTML page where a section changes based on user-selected options. Here is the part that displays the options: <div class="form-group-lg"> @foreach (var response in Model.ListResponses) { ...

How to retrieve the index of a click event following an AJAX request using jQuery

Can someone provide guidance on how to incorporate the line $(this).parents('#friendRequest').remove(); into the ajax success callback function? Also, how can I utilize $(this) to target the click event selector in the first line? jQuery(".notyA ...

Is it feasible to maintain a variable as a reference across views while utilizing ng-view?

I am facing a unique challenge: I have a webpage with two tabs that need to utilize ng-view from AngularJS. The twist is that both tabs must share the same variable, similar to referencing a variable in C# using the "ref" keyword. If you want to see an ex ...

Ways to receive JavaScript console error messages to aid in debugging your code

Currently, I am developing a Web Application and facing an issue with capturing console errors. Specifically, I need to capture errors related to network connectivity issues, such as when the network is down or slow causing responses from the server to be ...

AJAX Scripting: Receiving successful data retrieval

Is there a way to retrieve the success data returned by the AJAX call? I am trying to achieve the following: function myFunction(title) { var csrftoken = getCookie('csrftoken'); $.ajax({ url: 'call_details_cache/', ...

Retrieving the initial element from an array when a certain parameter is left blank

Looking at the following array: const data = [ {id: 1, courses: [{title:"course1.1", results:[]}, {title:"course1.2", results:[]}]}, {id: 2, courses: [{title:"course1.1", results:[]}, {title:"course1.2",results:[]}]}, ]; I am attempting to retriev ...