What is preventing the removal of the zeros during the process of combining a sorted array?

I've been tackling this challenge:

Below you'll find the code I've come up with so far:


/**
 Do not return anything, modify nums1 in-place instead.
 */
function merge(nums1, m, nums2, n) {
    nums2.forEach(i => {
        if (i > 0) {
            nums1.push(i)
        }

    })

    nums1.sort()


    for (let i = 0; i < nums1.length; i++) {
        if (nums1[i] == 0) {
            nums1.splice(i, 1)
        }
    }
};

This is the input ([1,2,3,0,0,0], 3, [2,5,6], 3)

The output I'm getting is: [0,1,2,2,3,5,6]

However, I expected it to be: [1,2,2,3,5,6]

Any insights on why this might be happening?

Thank you in advance!

Answer №1

You are iterating through an array and accessing the index of the original array, but changes are being made to the array itself.

For example, if you begin with [0,0,0,1,2,2,3,5,6], and then remove at index 0, you will have [0,0,1,2,2,3,5,6]. When i=1, you attempt to remove at index 1 resulting in [0,(here=>)0,1,2,2,3,5,6] and ending up with [0,1,2,2,3,5,6]. Additional indexing shows no more zeros.

To avoid this issue, I recommend using a reduce or map function to create a new array while keeping the original intact for indexing purposes.

Answer №2

The issue in your code arises from altering the length of the nums1 array using the splice method while looping over it with its initial length. This results in skipped indexes. To resolve this problem, you can add i-- after splicing the array.

function mergeArrays(nums1, m, nums2, n) {
    nums2.forEach((num) => {
        if (num > 0) {
            nums1.push(num);
        }
    });

    nums1.sort();

    for (let i = 0; i < nums1.length; i++) {
        if (nums1[i] == 0) {
            nums1.splice(i, 1);
            i--;
        }
    }
}

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

Transform the structure of the JSON data object

When I use the fetch() request, a JSON file is displayed. Here's an example of what I receive from the database: [ { "id": 3086206, "title": "General specifications" }, { "id": 3086207, "title": "Features ...

Using JavaScript regex to substitute white spaces and other characters

Here is a string I need to modify: "Gem. Buitentemperatuur (etmaal)" I want to remove all spaces, capital letters, and special characters from the string so that it becomes: "gem_buitentemperatuur_etmaal" ...

Troubleshooting: Node.js with Express - Issue with Loading Static JavaScript File in HTML

Despite trying numerous tutorials and following recommendations from various sources, my issue remains unresolved. I am attempting to create a basic static website using node.js and express to leverage server-side functionalities like file system access, d ...

Is there a way to make the checkbox and corresponding text display on a single line within my code snippet?

Bootstrap text-truncate is causing the checkbox and text to appear on separate lines in the following example. How can I adjust it to have the text right after the checkbox? <!DOCTYPE html> <html> <head> <meta charset="UTF-8" / ...

Creating a dynamic number of properties with different names in Typescript can be achieved by using a loop

I have a requirement for enabling type checking on a specific class Here is the relevant code snippet: class FlightFilter implements Filter { get filters() { return { departTime: { name: 'Departure Time', type: FilterTypes.Range }, ...

In Angular 4, you can easily preselect multiple options in a mat-select dropdown by passing an

Seeking assistance with setting the options of a mat-select in Angular 4. The issue at hand is as follows: 1. Initially, there are two variables: options and checkedOptions options: string[]; checkedOptions: string[] //Retrieved from the database; 2. T ...

The setState function in the useState hook is being called only one time when triggered by an EventListener

Within my functional component, I am utilizing the useState hook to store state. When the user reaches the bottom of the page, I want to dynamically add content. To achieve this, I implemented an EventListener for 'scroll' within a useEffect hook ...

When iterating through it, a sorted array in Javascript mutates the window object, but not in any

I am working with Python Django to create a view that returns JSON data to a template. In this template, I initialize a global JavaScript variable like so: <script type="text/javascript"> coordinates = {{ coordinates | safe}} </script> Th ...

Organize pictures and resize them to fit within a specific space

Seeking a solution that will organize various images of different sizes into a seamless rectangle display; Tried using Isotope (), but it doesn't automatically resize the images for perfect fit. Is there any effective JavaScript or PHP script recomm ...

Guide on utilizing JavascriptExecutor in Selenium for inserting text into a concealed text field with an unknown ID

In my current project, I encountered a search input box icon that needed to be clicked in order to open the input box. The issue was that the icon was hidden, so I decided to utilize JavaScriptExecutor to programmatically click on it and reveal the search ...

Add letters to the input field as soon as typing begins without the need to first click on the input field when

Take a look at the code below: document.addEventListener('keyup', logKey); function logKey($event) { var charCode = $event.keyCode; if(charCode > 31 && (charCode < 48 || charCode > 57 || charCode > 107 || charCode > ...

Retrieve file server domain using JavaScript or jQuery

I'm trying to extract the domain name without the "http(s)://www." from a file link. For example, if the script returns "example.com", I want it to parse through links like "http://www.example.com/file.exe" or "https://example.com/folder/file.txt#some ...

Conflicts arise when trying to create several objects with different material types in ThreeJS within the

Adding a star to the scene caused all objects in the scene to turn white and the perspective of the objects to glitch. Switching the materialStar to new THREE.MeshBasicMaterial fixed the rendering issue. It appears that the problem stems from having multip ...

Click on the div and any elements it contains in the CSS and JavaScript

I want to create a partially transparent overlay that covers an entire web page, similar to the example here: <div id="overlaySplash" onclick="clickHandler(this)"> <div id="insideBox"> [ insert clickable elements here with onclick="dos ...

Title remains consistent | Angular 4

Struggling to change the document title on a specific route. The route is initially set with a default title. { path: 'artikel/:id/:slug', component: ArticleComponent, data: {title: 'Article', routeType: RouteType.ARTICLE, des ...

Issue with AngularJS: Click event does not trigger compilation of variable in $compile element

I am trying to compile an element on click with a new variable, but after the first click, the variable appears in curly brackets {{variable}}. You can see it in action here var app = angular.module("myApp",[]); app.directive('tester',function($ ...

Identify when the user ceases typing in Angular 2

I am currently working on implementing a feature that detects whether the user is typing or not. I need to determine when the user has stopped typing for at least 3 seconds in order to perform certain actions. I have successfully detected when the user sta ...

Put a cookie in place to deter users from returning to the website

Looking for a way to prevent access to my contest site once the form has been submitted. Is there a way to achieve this? Thanks in advance ...

Right-align SELECT-OPTIONS text

Here are the screenshots of the form I'm currently working on. I am aiming to create a select box in the form where the text within the options is aligned to the right. After an option is selected, the chosen text should be displayed as illustrated i ...

Invoking a URL handler with JavaScript

Recently, I developed a Chrome extension that successfully identifies phone numbers in our CRM. I have tested it by using console.log and the results display correctly. Furthermore, we utilize Jitsi softphone which is set up with a URL handler. This means ...