Combining Arrays in Javascript With Sorted Elements

Currently, I am practicing JavaScript concepts by working on various LeetCode problems that I don't normally encounter in my daily work routine.

While starting with the easy section, I encountered an issue with merging arrays. I realized that I rarely use the splice method because I tend to iterate over elements and return a new array instead of modifying the original one. Additionally, I usually work with smaller datasets that do not require direct modification.

When testing with Jasmine, I encountered the following error:

Check for Sorted Merge

    ✗ Array values are merged and sorted
      - Expected $.length = 6 to equal 3.
      Expected $[2] = 2 to equal 3.
      Unexpected $[3] = 3 in array.
      Unexpected $[4] = 5 in array.
      Unexpected $[5] = 6 in array.

Below is the code snippet I was working on:

//////////////////
// INSTRUCTIONS //
//////////////////

// Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
// The number of elements initialized in nums1 and nums2 are m and n respectively.
// You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.

const nums1 = [1, 2, 3];
const m = 3;
const nums2 = [2, 5, 6];
const n = 3;

const mergeArray = (nums1, nums2) => {
  for (let index = 0; index < nums1.length - 1; index++) {
    if (nums2[index] >= nums1[index] && nums2[index] < nums1[index+1] ) {
      nums1.splice(index, 0, nums2[index]);
    }
  }
  return nums1;
};

module.exports = function () {
  describe("Check for Sorted Merge", () => {
    it("Array values are merged and sorted", () => {
      expect(nums1.concat(nums2).sort()).toEqual(mergeArray(nums1, nums2));
    });
  });
};

Answer №1

Perhaps we can streamline the process by taking advantage of the fact that both arrays are already sorted. Instead of comparing every element in one array with every element in the other, we can optimize the time complexity by maintaining a starting point and updating it each time we place an element from the second array into the first one. If this explanation is unclear, I can provide a more detailed explanation if needed.

const nums1 = [1, 2, 3]; // always sorted
const m = 3;
const nums2 = [2, 5, 6]; // always sorted
const n = 4;

const mergeArray = (nums1, nums2) => {
  let start_idx = 0;
  for (let num of nums2) {
    for (let idx = start_idx; idx < nums1.length; idx++){
      if (num <= nums1[idx]) {
        nums1.splice(idx, 0, num);
        start_idx = idx;
        break;
      }
      if (idx == nums1.length - 1){
        nums1.push(num);
        start_idx = idx;
        break;
      }
    }    
  }
  return nums1;
};

const res1 = nums1.concat(nums2).sort((a,b) => a-b);
const res2 = mergeArray(nums1, nums2);
console.log(res1, res2);

//JSON.stringify not ideal for arr/object comparison, but it works here for a quick check:
console.assert(JSON.stringify(res1) == JSON.stringify(res2), "sorts are not identical");

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

Animate the CSS when the content is within the viewport using pagepiling.js integration

I'm currently working on animating content as it enters the viewport. However, I've encountered an issue where jQuery (used to check if the content is in the viewport) isn't functioning properly alongside pagepiling.js (). I suspect this mig ...

employing the d3.queue method to defer execution until receiving the AJAX response

Seeking examples of integrating AJAX, d3, and PHP to extract data from a database and create graphs. Any guidance would be appreciated. I am currently using d3 to generate a force chart based on database information retrieved through AJAX and PHP. I have ...

Error: Webpack encountering reference errors when handling multiple entry points

Here is my setup in webpack.config.js: entry: { a:'./src/a.js', b:'./src/b.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name].bundle.js' } The content of a.js includes: const ...

Group a set of x elements together within a div, and then group a distinct number of elements together after every x-grouping

Is there a way to achieve a looping structure like this? For instance: Group every 2 divs into a new div, then (after every 2nd grouping) group every 3 divs together <div id="container"> <div></div> <div></div> ... </div& ...

Prevent zooming or controlling the lens in UIWebview while still allowing user selection

Is there a way to disable the zoom/lens on uiwebview without affecting user selection? I'm trying to avoid using "-webkit-user-select:none" in my css. -webkit-user-select:none ...

Tips for updating information within a vue-component

I am working on a Vue component where I retrieve data from localStorage. Here is how I handle it: if (localStorage.getItem("user") !== null) { const obj_user = localStorage.getItem('user'); var user = JSON.parse(obj_user); } else { ...

JavaScript - Modifying repeating numbers in an array

I have a list of numbers that repeats multiple times like this; numbers = [2,3,1,2,1,3,3,1,2] My goal is to increase each repeated number by 10 every time it appears. Therefore, the updated list should look like this; updated_numbers = [2,3,1,12,11,13,23, ...

Determine if the highest value in the array is at least double the size of all other numbers within the array

I am attempting to create a program that identifies the index of a number in an array that is at least twice as large as all other numbers. Below is the code I have written: def dominantIndex(self, nums): max_num = max(nums) max_i =nums. ...

Utilizing children as a prop within a Vue component

In React, I can create a FancyList component like this: const FancyList : React.SFC<{},{}> ({children}) => ( <ul> {...children} </ul> ); const FancyListItem : React.SFC<{text: string}, {}> ({children}) => < ...

Unraveling complex JSON structures

JSON data is available on a specific URL: { "href":"http:\/\/api.rwlabs.org\/v1\/jobs?limit=10", "time":18, "links": { "self": { "href":"http:\/\/api.rwlabs.org\/v1\/jobs?offset=0&am ...

What is the target of the `__proto__` attribute in a constructor function?

I'm taking the time to dive deeper into prototypal inheritance. I know that an instance's __proto__ property points to the constructor function's prototype object, but where does the constructor function's __proto__ property point to? ...

Is it possible to access Firebase data in Vue.js, with or without Vuefire, using a router parameter before the DOM is rendered?

When I navigate to a view from another view, I pass the itemId as a param value to vue router. My goal is to call firebase with that itemId in order to filter the data and use the filtered result/data in the UI. Specifically, I am utilizing vuefire. The ...

Only on mobile devices, Material-UI components spill over the screen

Update: This issue is isolated to one specific page. Other pages within the website are displaying correctly. Recently, I developed a web page using React and Material-UI. The main components utilized are Grid and Container. While the layout appears fine ...

Combining values from multidimensional arrays into a single row in PHP table

In my HTML table, there is a row that contains all the history pertaining to the entry description. This history data is stored in a separate database table from the main table data. GROUP_CONCAT(DISTINCT est.id, '|', est.date_estimate, '|& ...

What could be causing the malfunction in my JavaScript random selector?

Can anyone assist me with this issue? I'm attempting to implement JavaScript functionality to highlight randomly selected picks that I input, but it's not functioning correctly. Every time I inspect my JS code on the webpage, I encounter an erro ...

What is the process for invoking a NodeJS script within a personalized VSCode Extension?

Recently, I created a NodeJS script for one of my projects and now I'm looking to develop a VSCode extension around it. How can I integrate this script as a command within my custom extension? The goal is to have the script packaged along with the e ...

Always ensure that only one div is visible at a time

I am currently working on a project where I cannot use ng-cloak due to the way the css files are loaded. I have been exploring alternative solutions and have tried a few different approaches. My main goal is to ensure that two icons are never shown at the ...

Tips on altering a predetermined input text value using JavaScript

I have a question about using JavaScript. I am currently developing a tax calculation system. function calculateTax(){ var invoiceValue = document.getElementById("invoicevalue"); var ppn = document.getElementById("ppn"); var pph = document.get ...

Node.js causing excessive CPU usage due to repeated gettimeofday calls

Recently, I encountered a situation with a long-running node.js process that would occasionally spike to 100% CPU usage and stop responding to requests. In an effort to diagnose the issue, I used strace to inspect the process and discovered a series of get ...

Encounter the "Error: Source 'cloudsTileLayer-RasterSource' not found" message while trying to integrate a weather tile layer into Azure Maps

I have been working on a React application that utilizes the React-Azure-Maps npm package. My current challenge involves creating a weather layer, which I believe shares similarities with the sample code provided for layers. The code snippet responsible f ...