Insert an item into an array of objects at regular intervals of X objects

Here is an example of the array of objects I am working with:

[

 {_id: "59b6433532b60cfc0a253cec", description: "", imagepath: 
 "https://xxx.1", likes: 0, downvotes: 0}

 {_id: "59b6433532b60cfc0a253ceb", description: "", imagepath: 
 "https://xxx.2", likes: 0, downvotes: 0}

 {_id: "59b6433532b60cfc0a253cea", description: "", imagepath: 
 "https://xxx.3", likes: 0, downvotes: 0}

]

As I implement pagination, the array grows by adding another set of 10 objects each time.

My question is, how can I add a new object into the array when it reaches lengths like 20, 40, and so on?

The desired output would be:

[

 {_id: "59b6433532b60cfc0a253cec", description: "", imagepath: 
 "https://xxx.1", likes: 0, downvotes: 0}

 {_id: "59b6433532b60cfc0a253ceb", description: "", imagepath: 
 "https://xxx.2", likes: 0, downvotes: 0}

 {_id: "59b6433532b60cfc0a253cea", description: "", imagepath: 
 "https://xxx.3", likes: 0, downvotes: 0}

 ... <--- objects count now at 20 
 {new object 1}
 ... <--- objects count now at 40
 {new object 1} <--- same as above
]

Answer №1

To ensure the new object is inserted correctly, you can utilize the data.length % 20 === 0 function during each data retrieval or in a loop based on your preference. By using the modulus operator with 20 and comparing it to 0, the new object will be added when the length reaches 20, 40, 60, ....

var data = [

 {_id: "59b6433532b60cfc0a253cec", description: "", imagepath: 
 "https://xxx.1", likes: 0, downvotes: 0},

 {_id: "59b6433532b60cfc0a253ceb", description: "", imagepath: 
 "https://xxx.2", likes: 0, downvotes: 0},

 {_id: "59b6433532b60cfc0a253cea", description: "", imagepath: 
 "https://xxx.3", likes: 0, downvotes: 0}
];

var modCount = 0;
var objToInject= {type: 'blog_post'};

// Check if the length of the JSON array (data) is a multiple of 20, 40, 60, ...
if((data.length - modCount) % 20 === 0){
  data.push(objToInject);
  modCount++;
}

console.log(data);

Answer №2

Solution

To effectively address this issue, utilizing array reduce is the optimal approach.

Discover more about using array reduce here

Example

In this particular scenario, I will be inserting the text "test" after every 4th index.

var mainArray = [1,2,3,4,5,6,7,8,9];
var newArray = mainArray.reduce(function(carry, value) {
     if(carry.length % 4 === 0) {
        carry.push('test');
     }
     carry.push(value);
     return carry;
}, []);

You can achieve the desired outcome by adapting this method and replacing 'test' with your specific object or content.

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

Having difficulty implementing two-way binding on SELECT element within Angular JS programmatically

Struggling with implementing two-way binding for SELECT elements. Attempting to dynamically change the selected element through code. While I've come across examples on Stackoverflow for binding the change event for SELECT, finding resources on the ap ...

AngularJS directive for jQuery Handsontable is a powerful tool for creating interactive

I've been experimenting with using jQuery handsontable in conjunction with an angular directive, but I've encountered a strange issue. Whenever I type something into the cells, the characters appear outside of the table instead of inside it. Oddl ...

How to Extract a Link from JSON Data in React Native

My JSON data is formatted like this: orderData:"<p>Key VVV: 6326233</p> <p>Download link <a title=\"Movie\" href=\"https://play.google.com/store/movies/details/The_Angry_Birds_Movie_2?id=O_RbjOHHpIs&hl=en\" t ...

Creating JSON data in PHP is a straightforward process that involves encoding

I am looking to generate a JSON output that looks like this: { "id": "c200", "name": "Aneesh", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86e7e8c6e1ebe7efeaa8e5e9eb">[email protected]</a> ...

Encountering issues with updating state object in setState function

Review the code snippet below: {split.participants.map(friend => { return <div key={Math.random()} className="form-check my-2 d-flex align-items-center justify-content-between"> <div ...

Is it possible to utilize an await in an rxjs observable?

Implementing an interceptor for my HTTP requests requires the use of the access token from the user instance. Within my app component, I initialize the user: app.component.ts private async restoreUser(): Promise<UserModel | any> { // ... some vi ...

Issue with Ionic 4 button not triggering event when created using Jquery

Utilizing Ionic 4 in my current project, I have integrated it with Jquery. On the HTML page, a button is created using the following code: <ion-button (click)="event1()">EVENT1 </ion-button> In the .ts file for the page, a function is impleme ...

Nested jquery tabs

Similar Question: Unable to get jquery tabs nested I am trying to create a nested tab, but haven't found a satisfactory solution through my research. Can anyone provide me with some guidance? I have limited experience in JavaScript or jQuery prog ...

Leveraging ThemeProvider Parameters with Global Styled-Components

When working with styled-components, how can I access the props of the ThemeProvider in the context of global.js? For instance, in my theme.js file, I have ${props => props.theme.fonts.fontSize} set to a default font size of 16px. const theme = { ...

React and React Native not synchronizing with authentication context

It seems like there is an issue with the AuthContext not updating properly. Despite logging at various points, the user is still not being set. Here's a glimpse of the code in question: App.tsx export default function App() { const { user, setUser ...

Exploring the World of jQuery Caching and Navigating Through Objects

I'm interested in learning more about jQuery caching and how it can enhance performance. Can you explain how to properly utilize this technique? From what I understand, when using a jQuery selector, you're essentially searching the DOM to create ...

A guide on setting up fixed row numbers in MUI-X DataGrid

One challenge I am facing is rendering the row numbers in a table so that they remain static even when columns are sorted or filtered. I attempted to use the getRowIndexRelativeToVisibleRows method of the grid API, but unfortunately, it does not work as ex ...

Synchronously executing Twitter posts

Hello there! I've been using this code found here to embed Twitter posts on my website. It's been working perfectly on certain pages, like in the forums, but I've run into an issue while browsing through user profiles. The post history for e ...

What is the best way to retrieve JSON key/value pairs instead of an array?

I am working on retrieving data from a Google Spreadsheet using App Script and have set up a DoGet function. Currently, I am getting an array of data but I need it in JSON key-value pairs format. The table in my Google Sheets is structured as follows: Th ...

Sending text content using AJAX

Recently, I've delved into the world of AJAX and JavaScript while working on a project in JSP. My goal is to submit text entered in a textarea using a JavaScript button. The first submit button worked fine initially, but upon posting, I ended up with ...

The update feature seems to be malfunctioning within the MEAN Stack environment, specifically with node.js and angular js

Looking for some assistance as a beginner in the mean stack. I'm trying to update a record using the update function, but it's not working as expected. I need to update a specific object based on its ID, however, I'm encountering issues wit ...

Circular movement in ThreeJS within a specified duration

I am currently working on creating a circular motion for an object within a set time frame. This project involves designing a clock with smooth motion. Instead of simply updating the position to fixed coordinates every time .getSeconds() changes, I aim t ...

When implementing .forEach, an object within the array is mistakenly duplicated

Struggling to populate an array of objects with unique data using the .forEach function to display feedback in the Administrator page of my portfolio. However, encountering an issue where the objects from 'd' are getting duplicated in the 'f ...

Tips for layering one div on top of another div

I'm looking for guidance on how to position my button divs over my Trapezoids in an overlay fashion. Currently, I have set up an array to store the colors and utilizing the map function to match each button with its corresponding color type. When a ...

Tips for preventing cursor tooltips from going off the screen

I've been working on creating a popup box that displays text positioned away from an element when the cursor hovers over it. Check out a simplified demo here. Currently, the popup box collapses when it gets close to the bounding box. I'd like it ...