"Create a set of arrays within an object that are duplicates four times, and then dynamically manipulate the first item within each array

Here is the layout of my array object:

const foo  = {"data":[
[1,'asdf'],
[2,'lorem'],
[3,'impsum'],
[4,'test'],
[5,'omg'],
]}

I am looking to replicate each array four times and increment the first item by 0.1.

The final output should resemble this:

const foo  = {"data":[
[1.1,'asdf'],
[1.2,'asdf'],
[1.3,'asdf'],
[1.4,'asdf'],
[2.1,'lorem'],
[2.2,'lorem'],
[2.3,'lorem'],
[2.4,'lorem'],
[3.1,'impsum'],
[3.2,'impsum'],
[3.3,'impsum'],
[3.4,'impsum'],
[4.1,'test'],
[4.2,'test'],
[4.3,'test'],
[4.4,'test'],
[5.1,'omg'],
[5.2,'omg'],
[5.3,'omg'],
[5.4,'omg'],
]}

Answer №1

Let's simplify things by ignoring the wrapper object. How about trying this?

const data = [
  [1, 'asdf'],
  [2, 'lorem'],
  [3, 'impsum'],
  [4, 'test'],
  [5, 'omg'],
];

const out = data.map(([ num, ...rest ]) => {
  return Array(4).fill(0).map((_, idx) => {
    return [ num + ((idx + 1) / 10), ...rest ];
  });
}).flat(1);

console.log(out);

You could condense it into a one-liner if you really wanted to! *

data.map(([ num, ...rest ]) => Array(4).map((_, index) => ([ num + ((index + 1) / 10), ...rest ]))).flat(1);

* But please don't.


UPDATE: Let me break down the code above since there are multiple actions happening within those few lines.

We kick things off with a call to Array.map:

data.map((...) => { ... })

This operation creates a new array that matches the length of data, with each element being processed through the arrow function (a more concise way of writing function(...) { ... }) before being inserted into the new array.

Before delving into the body of the function, let’s examine its parameter more closely:

([ num, ...rest ]) => { ... }

// Alternatively in regular function format:
function ([ num, ...rest ]) { ... }

In this setup, we make use of both array destructuring and spread syntax. These two features, introduced in ES6, bring significant power to JavaScript. Array destructuring assigns values from an array directly to individual variables without needing an intermediate variable to store the entire array.

The function here only takes one argument (an array), but surprisingly, we have access to two variables within the function body. However, neither one represents the entirety of the array.

  • The first variable is num, which holds the value of the initial element in the array.
  • The second variable is rest, containing all remaining values in the array except the first one (which is stored in num). The spread syntax signifies “the rest of the values”, aggregating all elements following the first into rest.

Inside the mapping function, our starting point looks like this:

Array(4)

Array() serves as the constructor for JavaScript's underlying Array type. When provided with a single numerical argument, it initializes the array to that size.

We then proceed to apply Array.map() once again on the newly created array:

Array(4).map((_, idx) => { ... })

Note that this time, the function passed into map involves two parameters: _ and idx. Similar to before, the former represents the current element under processing within the array. Given that the array is currently empty, we disregard this element (hence naming it like so). The latter indicates the index of the present element within the array, crucial for calculating the updated value of num:

num + ((idx + 1) / 10)

This expression merges the original value of num for this particular set of new elements with the fractional part based on the current position in the inner array.

The modified num gets returned alongside the other values stored previously in rest:

return [ num + ((idx + 1) / 10), ...rest ];

Here, we solicit the spread operator again, implying that not just another array be returned as an element in the array, but rather each component within rest should get appended to the resulting array.

Hence, this complete internal section furnishes an array of arrays for a single fresh ‘group’ of elements:

return Array(4).map((_, idx) => {
  return [ num + ((idx + 1) / 10), ...rest ];
});

// Representation Upon Return:
[
  [ 1.1, "asdf" ],
  [ 1.2, "asdf" ],
  [ 1.3, "asdf" ],
  [ 1.4, "asdf" ],
]

Reinserting the outer cover yields:

data.map(([ num, ...rest ]) => {
  return Array(4).fill(0).map((unused, idx) => {
    return [ num + ((idx + 1) / 10), ...rest ];
  });
})

// Resultant Scenario:
[
  [
    [ 1.1, "asdf" ],
    [ 1.2, "asdf" ],
    [ 1.3, "asdf" ],
    [ 1.4, "asdf" ],
  ],
  [
    [ 2.1, "lorem" ],
    [ 2.2, "lorem" ],
    [ 2.3, "lorem" ],
    [ 2.4, "lorem" ],
  ],
  ...
]

All pertinent values have been correctly deduced, however, an unwanted extra stratum of arrays exists here. Most likely, you've identified the final chunk of code already:

.flat(1)

Array.flat() performs an elevation on the array according to a specified depth. A depth setting of 1 leads to every array being immediately inside the outer array getting their components incorporated into said outer array. For a depth value of n, this procedure recurs upon the output of the prior iteration exactly n times. Opting for a depth of

2</code in this situation would yield a solitary array structured thusly:</p>

<pre class="lang-js"><code>[ 1.1, "asdf", 1.2, "asdf", ... ]

Answer №2

How do you feel about this?

let x = 0;
let y = 0
bar.data[0][x].forEach(function(bar){
   while (y < 3){
      bar.data[0][x].push(bar);
       y++
   }
   x++
})

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

Is it better to use Asynchronous or Synchronous request with XMLHttpRequest in the Firefox Extension for handling multiple requests

As a newcomer to developing Firefox Add-Ons, my initial project involves calling an external API in two steps: Step 1) Retrieve data from the API. Step 2) Use the data retrieved in Step 1 to make another call to the same API for additional information. ...

Exploring promise chaining in mongoDB (and mongoose): A guide to effectively utilizing .save() following .then() and gracefully exiting a promise chain upon sending a response

Currently, I have implemented a code snippet for user signup that involves several steps. Initially, I validate the user input to ensure its correctness. Following this, I verify if the user already exists in the system, and if so, I return a response of 4 ...

An alternative to passing AngularJS expressions to PHP or Ajax

Within my PHP/HTML file, I have an AngularJS expression that looks like this: {{data.po_id}} This expression is included as <td>{{data.po_id}}</td> within a table row. I am trying to use this expression as a parameter for a PHP function in t ...

Internal server error encountered while making an AJAX call using AngularJS routing

I'm currently diving into AngularJS with a basic application focused on customers and their orders. The issue I'm encountering involves a table that showcases the list of customers along with a link to access their respective orders. However, upo ...

`How can I extract HTMLElements from slots in vue3?`

When attempting to develop a Layer component, I encountered some challenges. Here is the code: // Wrapper.vue <template> <slot v-bind="attrs"></slot> </template> <script lang="ts" setup> import { defi ...

JavaScript method to clear a variable

Can JavaScript prototype be used to add a method to a variable that is undefined? For instance, we can use the following code: var foo = "bar"; String.prototype.doTheFoo = function(){ console.log("foo is better than you"); }; foo.doTheFoo(); This c ...

``Change the color of the sections in a 3D pie chart on a Highcharts

I am looking to create a custom pie chart with two different colors: one for the main surface and another for the sides. Currently, I can only configure the lighter blue color for the main surface, but I would like to also change the darker blue color for ...

Iterating through the startPrivateConversation method in Botkit for a multitude of users

In order to send an update to all my users, I created a new bot controller in a separate js file. To achieve this successfully, I needed to implement a notification function inside the controller's rtm_open function. The goal was to iterate through th ...

Navigating back to the original page after venturing to a different one - react

In the header of each page, there is a 'Back' button that allows users to navigate back to the previous page. The function handleGoBack() is responsible for this: import React from 'react'; import { Button, Typography } from "@mate ...

MUI Autocomplete is failing to update the value when onChange event is triggered

I have successfully fetched autocomplete options from an API and it displays the pre-selected options from the API. However, I am encountering an issue where I am unable to delete or add a value (category) once selected. For an online demo, you can check ...

Utilizing JQuery to merge variable identifiers

Imagine a scenario where the variables are structured this way: localStorage.var1a = 0; localStorage.varnum = 1000; Now, consider the following code snippet: for(x = 1; x < localStorage.varnum; x++){ if(localStorage.var.x.a > 0){ localStora ...

Guide on executing a Python script using Node.js

I have set up a node.js server on Raspberry Pi and encountered an issue when trying to run a python script from it. Despite receiving the correct output from the client, the file fails to execute in this instance involving socket.io. The socket functiona ...

Tips on inserting a script prior to the body tag

It appears to be a straightforward process, but I am struggling to figure out what I am missing: var string1 = document.createElement('script'); $(string1).attr('type', 'text/javascript'); $('body').before($(string ...

Guide on toggling the button by clicking on the icon to turn it on or off

Within my angular application, I have implemented font icons alongside a toggle switch. Initially, the switch is in the ON state. The specific functionality desired is for clicking on an icon to change its color from white to red (this has been achieved) ...

Utilizing jQuery to add a class to an element when a different one is hovered above

I'm currently working on implementing effects on the edges of a webpage that will be triggered when a central div is hovered over. The main tool I'm using for this task is jQuery. Despite my efforts to diagnose the issue by using alerts in my Ja ...

What could be the reason why the toggleClass function is not being run

I've been running into a little issue with using the .toggleClass function in my code. It seems to work inconsistently, and despite reading various posts on the topic, I haven't found a solution that works for me. Could you provide some assistan ...

Building a bespoke search input for the DataTables JQuery extension

As the title indicates, I am in the process of developing a custom search box for the DataTables JQuery plugin. The default options do not suit my needs, and configuring the DOM is also not ideal as I aim to integrate it within a table row for display purp ...

Retrieving multiple checkbox values using JavaScript

When submitting a form using ajax and jquery, I encountered an issue with multiple checkboxes that are not posting values to the database. Here is the relevant HTML/PHP code snippet: while($row = mysql_fetch_assoc( $result )) { echo '<input ...

Filtering Arrays of Objects: A Guide to Filtering in JavaScript

Could really use some assistance with sorting an array of objects in javascript. My users array looks like this: var users = [ { first: 'Jon', last: 'Snow', email: '<a href="/cdn-cgi/l/email-protection" class="__ ...

The behavior of having two submit buttons within the $document.ready(function) in Jquery

In my code, I have implemented the behavior of two buttons, button1 and button2, within a $(document).ready(function). Whenever either button is clicked, an alert() function should be triggered. However, it seems that only button2 is functioning properly w ...