How can you add an object to an array in JavaScript without knowing the index?

I am working with an array

var prices = ['100','200','300','500'];

In my code, I am trying to insert a price if certain conditions are met.

var index = prices.indexOf(400);

if(index){  
       prices.splice(1, 0, '150'); 
         };



var index2 = prices.indexOf(200);

    if(index2){  
           prices.splice(3, 0, '600'); 
              };

One challenge I am facing is that I need to insert the value '600' after '300', but the index changes if the first condition is met. How can I ensure '600' gets added after '300' in this scenario?

Update

If the first condition occurs, the updated array should be:

// ['100','150','200','300','600','500']

If not,

// ['100','200','300','600','500']

Answer №1

Here is an example of HTML and JavaScript code:

<div id="demo"> </div>

In the JavaScript section:

var prices = ['100','200','300','500'];
document.getElementById("demo").innerHTML = prices;

function myFunction() {

    var index = prices.indexOf('400');
    if(index >= 0){
        prices.splice(1, 0, '150'); 
    }

    index = prices.indexOf('300');

    if(index >= 0){
        prices.splice(index + 1, 0, '600'); 

    }

    document.getElementById("demo").innerHTML = prices;

}

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

Explore the OData hyperlink within BreezeJS

I've been working on integrating the BreezeJS library with an SAP OData service. I have successfully managed to read entities, but I'm facing issues when trying to resolve linked objects. The EntityType I am dealing with is OrgObject. <Entity ...

Slideshow of table rows in HTML

On a webpage, I am populating an HTML table with a random number of rows ranging from 1 to 100. Regardless of the total number of rows, the requirement is to display only 10 rows at a time on the screen and then shift to the next set of 10 rows every 5 sec ...

Execute AJAX function following the completion of table loading from PHP in Ajax

I'm currently working on a shopping cart feature that involves calculating certain figures based on table values. The process involves loading the table using AJAX and PHP, which is functioning properly. However, I'm facing an issue where I nee ...

What is the best method for extracting JSON objects from an HTML page after executing a JS script with PhantomJS, and then transferring them to Java code?

I have been utilizing a JavaScript script code as mentioned in this specific answer. However, my goal is to avoid saving the resulting HTML page into an HTML file. Instead, I am looking to extract a JSON object from the <div class="rg_meta"> and tran ...

Having trouble adjusting the label fontSize in ReactJS when using semantic-ui-react?

Is there a way to decrease the size of the label for a form input? In this scenario, attempting to set the fontSize does not work: <Form.Input label="Username" style={{fontSize: '10px'}} /> Does anyone have any suggestions on how to res ...

Encountering a SyntaxError with the message 'Unexpected token' while trying to require a module in strict mode from JSON at position 0

Within the index.js file, the following code is present: 'use strict'; const config = require('./config'); In the config.js file, the code looks like this: 'use strict'; const config = new function() { this.port = 3000; ...

Challenges Associated with Promises in JavaScript

I'm having trouble with the last line of code in my program and I need some help figuring out how to fix it. Specifically, I know that the second "then" statement needs to return resolve() but I'm not sure how to go about implementing this. Any t ...

Store the Ajax JQuery selector within an array for safekeeping

I am completely new to working with Ajax and would appreciate some assistance in storing data from an Ajax request into an array. I have browsed through various solutions on this forum, but so far, I have been unable to resolve my issue. The Ajax respons ...

Invalid information is prevented from being submitted into the database by leveraging the power of jQuery and Ajax

I'm new to using jQuery and AJAX. I want to validate whether an email ID already exists in the database. To do this, I'm utilizing AJAX to check if the email exists or not. This verification takes place when a form is submitted, triggering the on ...

What is the reason behind the Python extension function failing when attempting to create an array of structs with a size exceeding 4

Currently, I am developing a Python extension module in C. I have encountered an issue where Python stops running when I attempt to declare an array of structs with more than 4 elements within a specific function of the module. The purpose of this module ...

React - Issue with Material-UI radio button group not filling button upon clicking

I've been working on an app using React and incorporating Material-UI components. In a specific section of the interface, there are four options that users can toggle between with radio buttons. Despite setting up the rendering correctly, I encountere ...

I wonder what the response would be to this particular inquiry

I recently had an angular interview and encountered this question. The interviewer inquired about the meaning of the following code snippet in Angular: code; <app-main [type]="text"></app-main> ...

Error: The variable "Set" cannot be found in the react.js code, specifically in Safari browser

An issue has been identified in Safari where a ReferenceError is thrown: "Can't find variable: Set" when using react.js. This error occurs only in Safari, while all other browsers work perfectly fine. The error message points to the main.js file which ...

Using an array from a MongoDB collection in Meteor

Trying to utilize a MongoDB collection with an array and incorporate it into the template. Index.html <body> {{>test}} </body> <template name="test"> {{ #each task}} <p>{{this}}</p> {{/each}} </template> The app ...

Having trouble invoking an established route within a different route in an Express JS project

While working with an Express JS application connected to a mySQL database, I encountered an issue when trying to fetch data from a pre-defined route/query: // customers.model.js CUSTOMERS.getAll = (result) => { let query = "SELECT * FROM custo ...

Execute the function when the form is submitted and show the total of the two values

I am currently working on a straightforward custom module for Drupal 7. This module takes two numeric values and upon submission, displays the sum of these values on the same page. While I have the form set up, it is not yet complete. I am facing some dif ...

Creating a spacious text box for an enhanced Ajax search feature

I'm currently working on an AJAX application that allows users to input the name of a movie, and then loads results from the database through jquery using a PHP API. However, I'm facing a challenge in implementing a text box with the following re ...

Performing a function when text is clicked: Utilizing AngularJS

My goal is to trigger a specific controller method upon clicking on certain text. This function will then make remote calls to another server and handle the display of another div based on the response. Additionally, I need to pass parameters to this funct ...

Having trouble with clearTimeout and clearInterval functions not functioning properly?

Currently, I've set up a countdown using both setInterval and setTimeout functionalities, and it seems to be running smoothly. However, I encounter an issue when trying to stop the countdown upon clicking a certain button; it pauses only after complet ...

Add a class individually for each element when the mouse enters the event

How can I apply the (.fill) class to each child element when hovering over them individually? I tried writing this code in TypeScript and added a mouseenter event, but upon opening the file, the .fill class is already applied to all elements. Why is this ...