What is the best way to swap out every instance of an array?

There are two arrays that I'm working with,

The first array is defined as var symbols = ['A', 'B'];, and the second array is defined as var num = ['3', 'A', '5', '4'];

I am looking for a solution to replace each element in the num array that matches an element in the symbols array by adding 10 to the index of that matching element in the symbol array.

So, the expected result would be:

num = ['3', '10', '5', '4']

How can I achieve this replacement for all occurrences?

Answer №1

Before asking for help, it's always best to attempt finding the solution on your own.

Nevertheless, here is a possible solution:

result = num.map((n) => {
    const index = symbols.indexOf(n);
    return index === -1 ? n : index + 10;
});

Answer №2

There are several ways to achieve this goal, each with varying levels of efficiency.

const symbols = ['A', 'B'];
const numbers = ['3', 'A', '5', '4'];

// Create a new array by filtering out elements that are present in the symbols array
const numbersWithSymbolsRemoved = numbers.filter(item => !symbols.includes(item));
// Now numbersWithSymbolsRemoved = ['3', '10', '5', '4']

// Modify the existing array directly by index
for (let i = 0; i < numbers.length; i++) {
    if (symbols.includes(numbers[i])) {
        numbers.splice(i, 1); // Remove item at current index
    }
}
// Now numbers = ['3', '10', '5', '4']

Answer №3

If you want to create a map, consider using an array called symbols where you can store elements along with their corresponding indexes. Then utilize the symbolMap map to generate the desired result in an array named num.

let symbolMap = new Map();
symbols.forEach((symbol, index) => symbolMap.set(symbol, index));

num.forEach((n, index) => {
    if (symbolMap.has(n)) {
        num[index] = symbolMap.get(n) + 10
    }
})

In this process, I am altering the original array. Alternatively, you can opt for using .map() instead of .forEach() if you wish to avoid modifying the original array.

let newNum = num.map((n) => {
    if (symbolMap.has(n)) {
        return symbolMap.get(n) + 10
    }
   return n
})

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

Refresh the page and witness the magical transformation as the div's background-image stylish

After browsing the internet, I came across a JavaScript script that claims to change the background-image of a div every time the page refreshes. Surprisingly, it's not functioning as expected. If anyone can provide assistance, I would greatly appreci ...

The problem with setting headers in Node Express MySQL: Error message indicating headers cannot be set after they have been sent

I'm currently working on a project using Node.js, Express.js, and a MySQL database. I have posts stored in the database that I want to display using the Pug.js view engine. I've managed to connect to the database and render the home route success ...

React Prop Local Modal Redux

Just diving into the world of React and Redux, and I'm a bit lost on how to effectively utilize both local properties and redux properties simultaneously. After trying different approaches without success, I'm reaching out for guidance. My goal i ...

Three pie or doughnut charts instead of one are utilized within Chart.js

Can multiple charts be nested inside one another? To see an example of a single chart and what I would like - where the first one is placed inside the second one and so on - please refer to this js fiddle. var data = [ { label: "title 1", value: ...

Clicking on the menu to reveal the dropdown options using JavaScript

I have created a drop-down menu for my website, but I am facing an issue. When I click on the links again, it does not work properly because I lack expertise in JavaScript. I would appreciate any help and suggestions from all of you. Thank you for your tim ...

What is the best way to remove a component from MongoDB after a specified period of time has passed

I am currently working on a basic web application using Node.js and MongoDB. I'm struggling with deleting entries from this field: shows what my webpage looks like After entering some data and clicking the button, it creates a new collection in my Mo ...

Looking for matching index in rotated array

Currently, I am working on a design with a reference rectangle (colored in red). Within a rotated container div (#map), I am trying to create a duplicate rectangle (in yellow) that matches the size and position of the original "base" rectangle, regardless ...

Retrieving the image source from the image element by utilizing $(this).find("");

Currently facing a challenge in retrieving the image source (e.g., ./imgs/image.jpg) from an image element. Managed to make some progress by using the following code: var image = document.getElementById("home-our-doughnuts-box-image").getAttribute("src" ...

A guide on utilizing ng-repeat to iterate through array values in Views

Need help with using ng-repeat on array values within an ng-repeat in VIEWS? The second ng-repeat is not functioning properly. Here is the value of generalDocument.documents: ["14-10-2015.xls","15-10-2015.xls","16-10-2015.xls"] <div class="box-body ...

MUI useStyles/createStyles hook dilemma: Inconsistent styling across components, with styles failing to apply to some elements

I have been trying to style my MUI5 react app using the makeStyles and createStyles hooks. The root className is being styled perfectly, but I am facing an issue with styling the logoIcon. Despite multiple attempts to debug the problem, I have not been suc ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

What is another option for toggling in jQuery?

After deprecating the toggle method, I found a new way to toggle div: $("#syndicates_showmore").on("click", function () { if (!clicked) { $('#syndicates').fadeTo('slow', 0.3, function () { $(this).css( ...

Query for string type data between specific dates in MongoDB

I have my data stored in this format on MongoDB: { "_id" : { "$oid" : "5385a437084ea4734b03374f" }, "linea" : 1, "egunak" : [ { "fetxa" : "2014/05/26", "turnoak" : [ { ...

Create a button toggle feature to dynamically display data for a specific record within an ng-repeat loop

Currently, I am facing an issue while implementing a start and stop timer in JavaScript for a list of records. To display all the items, I am using ng-repeat. Each repeated element has a Start/Stop toggle button. The problem arises when there are 4 records ...

How can I determine which component the input is coming from when I have several components of the same type?

After selecting two dates and clicking submit in the daterange picker, a callback function is triggered. I have two separate daterange pickers for SIM dates and Phone dates. How can I differentiate in the callback function when the user submits dates from ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

How come my dimensions are not returning correctly when I use offset().top and scrollTop() inside a scrolling element?

Currently in the process of developing a web app at , I am looking to implement a feature that will fade elements in and out as they enter and leave the visible part of a scrolling parent element. Taking inspiration from myfunkyside's response on this ...

Using AJAX to send a POST request with the PHP $_FILES superglobal while preventing the default form submission with the onclick

Seeking to implement a photo upload form using an AJAX script that is currently in place. Currently, I have the html form with a file input field. Upon submission, there is an onclick event triggering "PostForm(); return false;" This action directs to a ...

What is the process for creating a React Component with partially applied props?

I am struggling with a function that takes a React component and partially applies its props. This approach is commonly used to provide components with themes from consumers. Essentially, it transforms <FancyComponent theme="black" text="blah"/> int ...

Is there a way to trigger an Angular $scope function from a hyperlink in the current or a new tab using a right

Here is the HTML code I am working with: <a href="" ng-click='redirectToEntity("B-",obj.id")'>Click me and Process function and then redirect</a> While this code successfully processes the function and redirects to the desired page ...