Generate an array of identifiers from a pre-existing array

I am facing a challenge where I need to create an array of IDs for each element in an existing array whose size is unknown. The twist here is that every set of four elements should have the same ID.

As an illustration, if the original array (let's call it array1) contains 20 items, the new array would look like this: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5]

I attempted to achieve this using a for loop but struggled with how to assign IDs to every four elements without overriding them during iteration.

for(let i = 0; i < itemlist.length; i++) {newArray[i] = i; newArray[i] = i;newArray[i] = i;newArray[i] = i;} 

Answer №1

You can transform the current array by applying a function that generates unique IDs based on the index position in the original array

const someArray = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0];
const yourArray = someArray.map((el, i) => Math.floor(i / 4) + 1);

console.log(yourArray);

Answer №2

To efficiently create an array with only a quarter of the size, you can utilize the flatMap method to populate it with four elements per index.

function buildArray(size){
  return [...Array(size / 4)].flatMap((_,i)=>Array(4).fill(i + 1));
}
console.log(buildArray(20));

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

Validating form field values in JavaScript prior to submission

My website features a search box that allows users to search through a database of books. When utilizing the search feature, users are presented with the following options: Search Query (a text input field) Where to search (a select field with the option ...

Is it possible to bind parameters in the select clause using TypeORM?

I'm currently working on implementing a search feature using the pg_trgm module in my PostgreSQL project built with TypeScript and TypeOrm. My SQL query that works for me looks like this: SELECT t, similarity(t, 'word') AS sml FROM test_t ...

Difficulty in transferring a variable from my JavaScript file to my PHP file

Currently, I am utilizing the Instascan API to scan QR codes with the intention of sending the scanned content to my PHP file. However, regardless of whether I use POST or GET methods, the PHP file does not seem to recognize them and keeps expecting either ...

Changing the color gradient of a range column chart in ApexCharts

Currently, I am working on a project where I am trying to incorporate a waterfall chart using ApexCharts. Unfortunately, the Waterfall chart is not readily available with ApexCharts, so I am experimenting with modifying the range column chart into a Waterf ...

When using the Composition API in Vue 3, the "Exclude" TypeScript utility type may result in a prop validation error

Currently, I am utilizing Vue 3 alongside the Composition API and TypeScript, all updated to their latest stable versions. If we take a look at the types below: export interface Person { name: string; } export type Status = Person | 'UNLOADED&ap ...

How can Material UI React handle long strings in menu text wrapping for both mobile and desktop devices?

Is there a way to ensure that long strings in an MUI Select component do not exceed the width and get cut off on mobile devices? How can I add a text-wrap or similar feature? Desktop: Mobile: <FormControl sx={{ m: 1, minWidth: '100%', marg ...

Pressing a button meant to transfer text from a textarea results in the typed content failing to show up

Having trouble with a custom text area called a math field. I'm currently interning on a project to build a math search engine, where users can input plain text and LaTeX equations into a query bar. The issue I'm facing is that sometimes when th ...

TS2322 error: Attempting to assign type 'any' to type 'never' is invalid

Currently, I am utilizing "typescript"- "3.8.3", and "mongoose": "5.9.11". Previously, my code was functional with version "typescript": "3.4.x", and "mongoose": "4.x". Here is a snippet of my code: https://i.stack.imgur.com/j3Ko2.png The definition for ...

Tips for utilizing the keyword 'this' within a Promise

Seeking assistance with resolving an issue involving an undefined error when attempting to make an http request within a Promise function. The error occurs due to this.http.post being undefined, indicating that there is an issue with accessing this properl ...

How to utilize a PHP array within a Vue.js template

I have been exploring the realms of Laravel and vue.js recently and have encountered a challenge. Within my Laravel model, I have a PHP method that retrieves data from a database and organizes it into objects stored in an array. Now, my goal is to access t ...

Modal window closed - back to the top of the page

I am struggling with a simple modal popup window that does not maintain the scroll position when closed, instead returning you to the top of the page. I am looking for a way to keep it at the same scroll position without much knowledge of Javascript. You ...

Retrieving ng-pattern as a variable from a service

Hey there! I'm currently working on an application that requires extensive form validation across multiple pages. To streamline this process, I am attempting to extract validation patterns from a service used among the controllers. However, I've ...

The CORS Policy error message "The 'Access-Control-Allow-Origin' header is missing on the requested resource" in Next.js

Encountered an issue with CORS Policy error while attempting to redirect to a different domain outside of the project. For example, trying to navigate to https://www.google.com through a button click or before certain pages load. The redirection was handl ...

Unique alphanumeric code following the inclusion of a JavaScript file

I'm encountering an issue with a webpage that incorporates two JavaScript files. When inspecting it using firebug, I noticed that every time the page loads, these two files are included with the prefix ?_=someRandomNumber I'm unsure about the or ...

How to deal with an empty $_FILES array when there is file data present in $_POST

After reviewing multiple solutions, I noticed that they all utilize jQuery's .ajax() method. However, I have developed a more concise vanilla JS approach which has been quite successful for me. function ajax(options){ var settings = { met ...

Unexpected error when using Slack SDK's `client.conversations.open()` function: "User Not Found"

I am currently utilizing the Slack node SDK in an attempt to send private messages through a bot using user IDs: const client = new WebClient(process.env.SLACK_TOKEN); const sendMessage = async (userId) => { try { await client.conversations.open( ...

Unable to save captured signature image during saveEvent function in React Native

I am a beginner in the world of React Native and I am facing an issue with saving a signature image. It seems like the function responsible for this task is not being called properly. I suspect there might be an issue with the onPress event handler, as whe ...

A guide on triggering a new chart to appear beside the adjacent <div> when a bar is clicked in a highchart

I'm a beginner with Highcharts and I have a requirement for two charts (let's call them Chart A and Chart B). Creating one chart is straightforward. What I need is, upon clicking on a bar in Chart A, a new chart (Chart B) should open next to the ...

"Patience is key when waiting for the alert dialog response in Vuetify

I currently have a reusable component called Alert.vue. <v-dialog v-if="alertDict" v-model="alertDict.showDialog" max-width="460"> <v-card> <v-card-title>Title</v-card-title> & ...

Showing undefined or null values in React and JavaScript

My goal is to format undefined or null values by italicizing them. If the value is an empty string, it should be displayed as is. If it has a value, that value should also be displayed as is. However, I am encountering an issue where null or undefined val ...