Fill every empty element with elements from another array

I'm struggling to grasp the concept of arrays. I have two arrays and I want to replace the null elements in one with the elements from the other. Here is what I have currently:

var arr1 = [1,2,3,4]
var arr2 = [null, 99, null, null]

arr2.map((item) => {
  if (item == null) {
    arr2 = arr1.splice(item, 1)
  }
})

console.log(arr2)
// The output is [3]. I was expecting 1, 99, 3, 4

I chose to use splice as I felt it was the most appropriate method for this task. I also used .map, but it isn't a required method.

I would appreciate any guidance to a related question that has already been answered, but I couldn't find one due to English not being my primary language.

Answer №1

Your code will execute splice(null, 1) on arr1 and then replace the entire arr2 three times.

map is a function that allows you to iterate through an array and provide a replacement for each element. Make sure to use it correctly, as shown below:

let arr1 = [1,2,3,4]
let arr2 = [null, 99, null, null]

arr2 = arr2.map((item, i) => item === null ? arr1[i] : item )

console.log(arr2)

Answer №2

Instead of using the splice method, you can achieve the same result by using a ternary operator to extract the value you need:

let array1 = [5, 7, 9, 2];
let array2 = [null, 18, null, null];

array2 = array2.map((value, index) => value === null ? array1[index] : value);

console.log(array2);

Answer №3

You're heading in the right direction, however, the callback function in the map method should return the element that will be included in the new array. Here's a revised version:

arr2 = arr2.map((value, index) =>
    value != null ? value : arr1[index]
});

Answer №4

When both arr1 and arr2 are of equal size, you can use the following method:

for(var i=0;i<arr2.length;i++){
  arr2[i]= arr2[i] || arr1[i];
}

The reason for using a for loop is to provide a clear understanding of how arrays operate, especially for those new to working with them. The || operator, also known as the null-coalescing operator, assigns the first truthy value as the result of the operation.

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

How to retrieve a randomly selected subset from a MongoDB database using Express

Recently, I have been diving into the world of coding and decided to create a trivia game using Mongo, Express, and NodeJS. The game pulls random trivia questions from a database, allows users to input answers, and verifies if they are correct. However, I ...

Unable to change the structure of a multidimensional array in PHP

I am faced with the challenge of working with two arrays. The first array ($dcel) is structured like this: Array( [1] => Array ( [V1] => 5 [V2] => 2 [F1] => 4 [F2] => 1 [P1] => 7 [P2] = ...

AngularJS uses variables defined by using curly braces like {{"message"}}

I am currently utilizing the following code snippet to monitor route changes: $scope.$on('$routeChangeStart', function (event, toState, toParams, fromState, fromParams) { //content $log.log(toState); } Whenever I print out "toState ...

How to automatically close a JavaScript popup once a form is submitted and refresh the parent page

I am facing an issue with a popup on my website. I have a separate page called math.ejs that pops up when a button is pressed on the index.ejs page. However, after clicking the submit Ok button in the math.ejs popup, I want it to close and display the calc ...

Transmission of state modifications in React

My React project is organized with the following hierarchy: The main A component consists of child components B and C If I trigger a setState function in component B, will components A and C receive notification and potentially re-render during the recon ...

Choose a radio button from a React Native FlatList

I am new to React Native and I'm working with the expo-radio-button component. However, I'm facing an issue where I can't seem to select only one radio button at a time in a flatlist. When I try to select a single button, it ends up select ...

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...

Using a conditional statement to wrap a react Route

Currently, I am facing a challenge while working with react router. Initially, I had two distinct components being rendered under the same route - one with a parameter and one without (this was how the routes were distinguished). Now, my goal is to add opt ...

Unable to apply CSS modifications to child elements in AngularJS

angular.element($document[0].querySelector("table > tbody > tr")).mouseover().css("background-color", "red"); <table> <thead> <tr> <th>Name</th> < ...

I have the ability to effectively open a modal whenever necessary, but I struggle with closing it afterwards

I've been working on implementing a React bootstrap modal, and while I can successfully open it when needed, I'm running into issues with closing it. I'm not sure what mistake I might be making. Here's my markup: <Modal show={this. ...

What strategies can be employed to mitigate the activation of the losing arm in a Promise.race?

My current task involves sending the same query to multiple identical endpoints (about five) across various Kubernetes clusters. The goal is to aggregate the results without any delays and report failures to the user while continuing with the process seaml ...

passport.js and express: TypeError - Router.use() must be given a middleware function, but instead received a ' + gettype(fn)

I encountered an error while using passport.js with Express.js TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) This issue arose from the following code: passport/local.js var LocalStrategy = require("passport ...

The error message "trying to access markers property of undefined in the render function" occurred

I encountered this error while running my react-native component and need assistance. An error stating "undefined is not an object (evaluating 'this.state.markers.map')" occurred. This error appears in the following locations: c:\proje ...

Tips for making a hide and reveal FAQ section

Currently working on creating a FAQ page for my website, I ran into a challenge. My goal is to have a setup where clicking on a question will reveal the answer while hiding any previously open answers. So far, I have managed to achieve this functionality p ...

Tips for incorporating side effects into an observable property?

I am relatively new to Mobx and I need to automatically call a function when this observable array is updated. The observable array: @observable Todos = [] I have many functions to manage this array (addTodo, removeTodo, ...) and I would like to avoid ...

Images within inline blocks appear to be extending beyond their containing div as though they are

When I check my website in various browsers such as Firefox, IE, Edge, and Safari, I noticed that the images in the "My Specialties" section of the left column are extending outside of the div instead of fitting within it. This problem also occurs in Chrom ...

Troubleshooting $templateCache not functioning correctly within the Angular.js angular-config

I keep encountering an error message that says "angular.min.js:6Uncaught Error: [$injector:modulerr]" whenever I try to implement $templateCache in my app.config block. Interestingly, when I remove the $templateCache parameter from app.config, the errors d ...

Adding a nested data structure in a Meteor application

In my mongo collection, I have a document named exam. // meteor:PRIMARY> db.exam.find() { "_id" : "RLvWTcsrbRXJeTqdB", "examschoolid" : "5FF2JRddZdtTHuwkx", "examsubjects" : [ { "subject" : "Z4eLrwGwqG4pw4HKX" }, ...

When the div element reaches the top of the page, it sticks to the top and is only displayed when the user

In the center of a full-screen hero section, there is a form. When it reaches the top, its position becomes fixed and additional classes are added through a script - such as shrinking its height and adding a background. What I aim to achieve is for the fo ...

Encountered an error in the React.js app where it cannot read the property 'Tag' of undefined from domhandler

I recently encountered an issue with my react.js project, which utilizes domhandler v4.2.0 through cheerio. Everything was running smoothly for months until one day, I started getting this error during the build process: domelementtype package includes a ...