Tips for inserting a value into a specific location within an array using JavaScript

I am working with an array of objects that looks like this:

const array = [
  { id: 1 },
  { id: 2 },
  { id: 3 },
  { id: 4 }
];

My task is to add a new entry to this array, but it needs to be inserted at a specific position. For instance, when adding { id: 5, after_id: 2 }, the new object should be placed between ids 2 and 3. Is there a recommended method for achieving this?

Answer №1

@p.s.w.g has shared a great solution in the comments, but I wanted to present my original approach as an answer now that the question is reopened.

To tackle this problem, you can leverage the some method to loop through the array until the desired index is found. Once located, you can slice the array and insert the new item at the specified index:

const arrayTest = [{
    id: 1
  },
  {
    id: 2
  },
  {
    id: 3
  },
  {
    id: 4
  }
];

const insertAfterId = (array, item, idAfter) => {
  let index = 0;
  array.some((item, i) => {
    index = i + 1;
    return item.id === idAfter
  })

  return [
    ...array.slice(0, index),
    item,
    ...array.slice(index, array.length),
  ];
};

const result = insertAfterId(arrayTest, {
   id: 6
}, 2)
console.dir(result)

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

Reset the jQuery star-rating plugin

I came across a useful plugin for star ratings called JQuery Star Rating by Daniel Upshaw. My question is, how can I reset the stars in a form using this plugin? $("#btn-reset").on('click', function() { //resetting other inputs $('#st ...

What is the correct way to use fitBounds and getBounds functions in react-leaflet?

I'm struggling with calling the fitBounds() function on my Leaflet map. My goal is to show multiple markers on the map and adjust the view accordingly (zoom in, zoom out, fly to, etc.). I came across an example on How do you call fitBounds() when usi ...

Can someone show me how to use the IN operator in a PostgreSQL query in an Express.js (Node.js

My Approach to Writing Code var employees=[1,2,3]; await client.query( "SELECT user_id FROM group_user WHERE user_id IN($1)", employees ); An error is thrown indicating that only one parameter needs to be provided ...

The compatibility issue with Internet Explorer and Arabic text is impeding the functionality of jQuery AJAX

$('#search_text').keyup(function() { var search_text = document.getElementById('search_text').value; $.ajax({ url:"jx_displayautocompletelist.php", data: 'text='+search_text, success:function(result){ $ ...

Arrange fixed-position elements so that they adhere to the boundaries of their adjacent siblings

Is there a way to keep two fixed elements aligned with their sibling element on window resize? <div class="left-img"> IMAGE HERE </div> <!-- fixed positioned --> <div class="container"> Lorem ipsum... </div> <div class=" ...

How can one transform a json object into a json string and leverage its functionalities?

I recently encountered an issue with a JSON object that contains a function: var thread = { title: "my title", delete: function() { alert("deleted"); } }; thread.delete(); // alerted "deleted" thread_json = JSON.encode(thread); // co ...

Is it possible to utilize a variable from a Higher Order Function within a different generation function?

I am facing a dilemma with the need to utilize email = user.email in newcomment['comments/'+id] = {id,comment,email,date}. However, I am unable to incorporate email = yield user.email or yield auth.onAuthStateChanged(user => {email = user.em ...

Notify immediately if there is any clicking activity detected within a designated div container

I am looking to trigger an alert when a specific div is clicked. Here is the scenario: <div class="container"> <div class="header"> <h1>Headline<h1> </div> <div class="productbox"></div> </div> I have succ ...

Attempting to conceal the select input and footer components of the Calendar component within a React application

I am currently working on customizing a DatePicker component in Antd and my goal is to display only the calendar body. Initially, I attempted to use styled components to specifically target the header and footer of the calendar and apply display: none; st ...

Looking to test form submissions in React using Jest and Enzyme? Keep running into the error "Cannot read property 'preventDefault' of undefined"?

Currently, I am developing a test to validate whether the error Notification component is displayed when the login form is submitted without any data. describe('User signin', () => { it('should fail if no credentials are provided&apos ...

Learn how to extract information from a JSON data array and seamlessly integrate it into an ObservableCollection using C# in Xamarin

Reviewing my JSON data { "found": 501, "posts": [ { "ID": 2500, "site_ID": 1, "date": "2014-09-26T15:58:23-10:00", "modified": "2014-09-26T15:58:23-10:00", "title": "DOD HQ Visitors Parking", "metadata": [ { "id": "15064", "key": "city", ...

What is the proper way to leverage the global 'window' object within Angular?

I'm attempting to utilize the method "window["initMapCallback"]" to invoke and monitor for "initMapCallback" in a separate file. However, I am encountering an error message in the debugging console that states Query - How can I properly implement thi ...

Troubleshooting Query Param Problems in EmberJS Route Navigation

("ember-cli": "2.2.0-beta.6") A search page on my website allows users to look for two different types of records: Users or Organizations. The URL for this search page is /search and I have implemented query parameters to maintain the state and enable ba ...

Search for all documents in MongoDB and update all of them except for one

After performing a database lookup, I am receiving an array of objects as a result. [ { name: "test", services: { credentials: "123456" } }, { name: "test1", services: { credentials: "1 ...

Transfer the selected user content from one canvas to another

After successfully implementing a simple selection area on canvasA, I encountered an issue with copying the area to canvasB. The user is supposed to select an area and then see that selection appear on another canvas once they finish making the selection b ...

Implementing Various Conditions in ng-if Using AngularJS

I have a scenario in my AngularJS application where I need to display different buttons based on the value of type. If type === 'await_otp', then I should display two buttons (resend OTP and cancel), if type === 'submitted', then only t ...

JavaScript - The AJAX response is consistently after being undefined

I am encountering an issue with the following functions: function get_non_authorized_bulk_edit_option_values() { var modificable_column_names = get_write_user_values(); alert(modificable_column_names); } The above function is calling this ...

NodeJS's pending ajax post using SailsJS

I'm experiencing an issue with processing AJAX data in my sailsJS app. The ajax post data always stays in the pending state, here is the code from my view: <script type="text/javascript"> $('#submit').click(function(){ $.ajax ...

Transforming a simple MySQL query into a structured nested JSON format

Is there a way to easily reorganize data without using complex for loops (perhaps with Underscore.js or refining the MySQL query)? I have data formatted like this: [ { "J_NUM": "BOAK-1212", "X_DUE_DATE": "2012-06-20T00:00:00.000Z", "X_LEAD_T ...

Guide to verifying all chosen options in a multiple select field using EJS

I am looking for the most effective way to check all selected options in my select dropdown when data is being edited. Here is an example of my select dropdown that supports multiple selections: <select name="tags[]" class="multi-select" multiple="" i ...