Expanding a list of object arrays through iteration: A step-by-step guide

// Initializing with one object
let posi_val=[{top: '3px', left: '2px'}];
// Adding another object in the loop
for (let i = 1; i < n; i++) {
    posi_val.push({ 
        top: `${posi_val[i - 1].top.slice(0, -2) * 2}px`,    
        left: `${posi_val[i - 1].left.slice(0, -2) * 2}px`  
    });
}

Hey everyone! The code snippet above is part of a CSS class creation process to generate multiple red dots at different positions. I'm looking for guidance on how to expand the array of objects like the ones shown above using a for loop, where each subsequent value for 'top' and 'left' properties will be twice the previous value (e.g., 3, 6, 12 px and 2, 4, 8 px).

I attempted using JSON.parse to reconstruct the entire string, but it got quite confusing. Are there simpler methods available to construct this array efficiently? You can check out a demo on CodePen here.

Answer №1

Is this something you were looking for?

console.log(  creatingGrid( 5 )  )

function creatingGrid( counter )
  {
  let top= 3, left= 2, result= [];
  for(let i=0;i<counter;i++)
    {
    result.push( {top:`${top}px`,left:`${left}px`} );
    top *=2, left *=2;
    }
  return result
  }
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

Can you achieve the same outcome with a single line of code?

All values are in binary and left shift equals multiplication by 2.

const creatingGrid = length => 
  Array.from({length},(_,i)=>({top:`${3<<i}px`,left:`${2<<i}px`}));

console.log(  creatingGrid( 5 )  )
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}

Answer №2

Is this meeting your expectations?

function calculateCssPositions(initialTop, initialLeft, count) {
    let positions = [];
    for(let i=0; i<count; i++){
        let cssObject = { top: `${initialTop}px`, left: `${initialLeft}px` };

        initialTop += initialTop;
        initialLeft += initialLeft;

        positions.push(cssObject);
    }
  
  return positions;
}

// Using the function 
console.log(calculateCssPositions(3,2,3));

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

Tips for eliminating the bottom border on a nav-tab in Bootstrap 4

When a vertical navigation menu item is selected, a border appears below the item. How can I remove this border? .nav-tabs li, .nav-tabs li a { border-bottom: none; } Here is a picture of the border: ...

Validation of forms in AngularJS/HTML5 that are nested within one another

Just starting out with AngularJS and experiencing issues with HTML5 nested form validation. I currently have 2 forms; mainFrm (parent form) and stateFrm (a child form). I am struggling to validate each form within its own scope. <form id="mainFrm" ng- ...

What is the purpose of using a callback like "function(value) {return my_function(value);}" in node.js programming?

Hello, I am brand new to JavaScript so please bear with me if my question seems too simple. Let's say I have a list of strings and I want to filter them based on a function f that takes a string as input and returns a boolean. This approach works: f ...

What is the best way to place a transparent navbar on top of a hero image while also adding a functional button to the hero image?

My navigation bar is set to be transparent on top of my hero image, but the buttons on the hero image are not clickable. The nav-bar has a z-index of 1, while my hero image, text, and button have a z-index of -1. This setup causes the button to be unclick ...

Tips on transforming JSON output into an array with JavaScript

Looking for a solution to convert a Json response into an array using JavaScript. I currently have the following json response: ["simmakkal madurai","goripalayam madurai"]. I need to transform these results into an array format. Any suggestions on how I ...

Create text that alternates between blinking and changing content simultaneously

I'm currently working on a website and I am curious about how to achieve the effect of making text blink and change content simultaneously, similar to what is seen on this particular website . Sorry for not being more specific in my question. Thank yo ...

Ways to incorporate the setTimeOut function

<body> <script> $(window).scroll(function() { $('#csgo').each(function(){ var imagePos = $(this).offset().top; var topOfWindow = $(window).scroll ...

Developing jpg/png images from .ppt/pptx files with Django

I currently have a PowerPoint file saved on Dropbox at "". My goal is to convert this presentation file into individual slide images (jpg/png..) within my Django template or using a Django def function. Once I have converted the slides, I plan to utilize ...

Retrieve the unique payment ID generated from the database and present it on the frontend

Greetings, I am currently working on integrating a payment processor and I require the automated generation of the corresponding payment ID in the backend. On the frontend side, I have implemented JS to request data from the backend, but I'm facing ...

Error: An unexpected symbol '<' was encountered after the build process in Vue.js

I just finished deploying a MEVN stack application to heroku. While everything is functioning properly locally, I am encountering a blank page and the following errors in the console post-deployment: Uncaught SyntaxError: Unexpected token '<' ...

What is the best way to transfer the content from a tinyMCE textarea editor to an inner controller using Symfony3 and Ajax

I have two small rich text editors identified as #homepage and #thankyoupage. My goal is to submit the content of these TinyMCE text areas to a Symfony controller. Below is my front-end implementation: https://i.stack.imgur.com/TE1Ys.jpg Currently, I am ...

Tips for creating sliding header content alongside the header

Is it possible for the content in the header to scroll up, displaying only the navigation list and hiding the logo when a user scrolls on the website? Currently, while the header background slides up, the content within the header remains in place. I feel ...

Tips for passing parameters in an AJAX request

I have a single AJAX call that requires passing parameters to my function. Below is the AJAX call implementation: $.ajax({ url: 'lib/function.php', data: { action: 'getStoreSupplyItems', id: store_id, ...

Setting the second tab as the primary active tab

I am currently working on a script that is well-known, and everything is functioning perfectly. However, I want to change it so that when the page is first opened, it displays the second tab instead of the first one (the first tab being a mail compose tab ...

Displaying a div upon hovering over another div is resulting in numerous server requests and a flickering effect

I am attempting to create a hover effect where one div floats next to another. The layout of the divs is like a grid, placed side by side. Check out my code on this fiddle. Using plain JavaScript, I want to display a second div (div2) floating next to div ...

One way to retrieve API responses in node js is by utilizing callback functions

I am currently exploring callback functions and utilizing the request module in node js to retrieve information. As Javascript is asynchronous, I am struggling with how to properly return my response. Below are snippets of my code. In my app.js file: var ...

Is it possible to extract around 10 variables from a JavaScript code, then display them on a webpage after execution?

I have just completed writing a Javascript code with around 3,000 lines. This code contains over 60 variables, but there are a few specific variables that I would like to display on my main HTML page. These variables include: totalTime longitudinalAcceler ...

What are the PropTypes for Animated.Values?

My parent component has an Animated Value defined like this: const scrollY = new Animated.Value(0); console.log(scrollY); // 0; console.log(typeof scrollY); // object; Next, I want to pass this value to a child component: <ChildComponent animatedVal ...

Obtain an individual item from the reducer array

I am working on a company reducer that will store an array of companies. To optimize performance, I aim to fetch only the necessary company object from my API when a user navigates to /company/name. This way, if a user visits the same company page multiple ...

Tips for maintaining the active tab in Jquery even after the page is reloaded, especially for tabs that are constantly changing

$(document).ready(function(){ $('.scroll_nav li a').click(function(){ $('li a').removeClass("active_scroll"); $(this).addClass('active_scroll'); $('ul li .btn-br_all_gun').click(function(){ ...