Iterate through the array and add each number to a separate array

I am currently facing an issue with the code snippet provided below.

    var array = [1, 3, 2]
    var newArray = []

  getNewArray() {
    for (let i = 0; i < array.length; i++) {
      for (let x = 0; x < array[i]; x++) {
        this.newArray.push(array[i]);
      }
    }
    console.log(this.newArray);
  }

My goal is to iterate through the numbers in an array based on their values, producing results like the following:

(3) [{…}, {…}, {…}]
   0:
     count:(1) [1]
   1:
     count:(3) [1,2,3]
   2:
     count:(2) [1,2]

However, the current output I am getting is different from what I expected:

(4) [1, 2, 2, 1]
  0: 1
  1: 2
  2: 2
  3: 1

Answer №1

If you want to take advantage of ES6 features, a useful approach is combining the use of .map and Array.from.

Suggestion:

  • Utilize Array.map to iterate through each item.
  • Use the item as the length parameter to create a new array with Array.from.
  • Include a mapper function to populate the new array.

var array = [1, 3, 2];
var result = array.map((item) => Array.from({
  length: item
}, (_, i) => i + 1));
console.log(result)

Answer №2

Give this a shot

let numbers = [2, 4, 6]
let newNumbers = []

function createNewArray() {
for (let i = 0; i < numbers.length; i++) {
let temp = [];
for (let x = 0; x < numbers[i]; x++) {
temp.push(x+1);
}
this.newNumbers.push(temp);

}
}
createNewArray();
console.log(this.newNumbers);

Answer №3

let numbers = [2, 6, 4];
let updatedNumbers = [];

function updateNumbers() {
    for (let j = 0; j < numbers.length; j++) {
      let tempNumbers = [];
      for (let y = 0; y < numbers[j]; y++) {
        tempNumbers.push(numbers[j]);
      }
      updatedNumbers.push(tempNumbers);
    }
    console.log(this.updatedNumbers);
}

updateNumbers();

Answer №4

Utilizing the power of arrays

let numbers = [5, 7, 9]
let newNumbers = []

const createNewArray = () => {
  newNumbers = numbers.map(num => Array(num).fill().map((_, index) => index+1))
  console.log(newNumbers);
}
createNewArray()

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

Partial functionality achieved by integrating Bootstrap for a modal form in Rails

Having an issue with a form in a partial view on Rails 3.2.3 utilizing the bootstrap 2.0.2 modals #myModal.modal .modal-header .close{"data-dismiss" => "modal"}= link_to "x", root_path %h3 Add Tags .modal-body = form_tag '/tagging& ...

Clear out a collection in backbone.js

I am looking to clear out a collection by removing each item in sequence. this.nodes.each(function(node){ this.nodes.remove(node); }, this); The current method is ineffective as the collection length changes with each removal. Utilizing a temporary arr ...

Ways to slow down page transition on NextJs

I'm currently working on securing my private pages using a HOC withAuth. While the protection is functioning correctly, I am looking to avoid users seeing a loading screen for a split second while the access token is being retrieved from local storage ...

Accessing an array of objects within nested objects results in an undefined value

I am facing an issue with my JavaScript object that is retrieved from MySQL. The object has a property which contains an array of other objects, as demonstrated below: parentObject = { ID: "1", Desc: "A description", chi ...

Using JavaScript to launch a new window with an array of parameters

I am working on an asp.net mvc 3 application that has an Action Method for handling GET requests and returning a page. The code snippet is shown below: [HttpGet] public ActionResult Print(IEnumerable<string> arrayOfIds) { ....................... ...

OBJ Raycasting in Three.js

Greetings! I encountered an issue while working with three.js in my project. Specifically, I was trying to select a custom mesh that I loaded from an OBJ file. To troubleshoot, I set up a simple raycaster, a cube, and my custom model (which is also a cube ...

The mystery behind the enigmatic combination of ajax, JQuery,

Seeking Assistance! All fields are displaying undefined values function UpdateData(){ var id = $('#id').attr('value'); var name = $('#name').attr('value'); var department = $('#departament'). ...

Error: Morris.js is unable to access the property 'x' because it is undefined

Seeking assistance in utilizing Morris.js to create an area chart using data from a JSON file. The JSON data is as follows: [{"period": 0, "time": 121.0}, {"period": 1, "time": 102.0}, {"period": 2, "time": 104.0}, {"period": 3, "time": 91.0}, {"period": ...

How to achieve horizontal auto-scrolling in an image gallery with jQuery?

Hey there, I'm currently working on an Image Gallery project. I have arranged thumbnails horizontally in a div below the main images. Take a look at this snapshot img. My goal is to have the thumbnails scroll along with the main pictures as the user ...

Creating a CSV download feature with ReactJS is simple and incredibly useful. Enable users

Despite searching through various posts on this topic, I have yet to find a solution that addresses my specific issue. I've experimented with different libraries and combinations of them in an attempt to achieve the desired outcome, but so far, I have ...

Limits on zooming with THREE.js Orbit controls

I've encountered an interesting limit while using Orbit controls. The zooming functionality is tied to the radius of the spherical coordinates of the camera in relation to the orbiting axis. Here's how it functions: Whenever the user scrolls, t ...

retrieving the site's favicon icon

Currently, I am attempting to extract favicons from website URLs using the HtmlAgilityPack library. While I have been successful in retrieving some favicons, there are still some that remain elusive. I suspect that the inconsistency lies in the implementat ...

The value from the angular UI bootstrap datepicker is unavailable when using a JQuery expression

I have a question regarding the datepicker feature from the Angular UI bootstrap library. The documentation can be found here. After selecting a date using the datepicker, I am facing an issue with retrieving the text input using jQuery expressions. When ...

The functionality of a Google chart is determined by the value of the AngularJS $scope

I recently started working with AngularJS and Google charts. I've successfully created a Google chart using data from AngularJS. It's functioning properly, but now I want to make the chart dynamic based on my Angular Scope value. I have a filter ...

Removing zeros from a one-dimensional tensor in TensorFlow.js: A step-by-step guide

If I have a 1D tensor (distinct from an array) with the values [0,2,0,1,-3], my goal is to retrieve only the non-zero values. Using the example provided, I want to receive [2,1,-3] as the output. Is there a way to achieve this in TensorFlow.js? ...

Is there a way to use code to target a mesh in a three.js scene when a button is clicked?

When a button is clicked, I want a Three.js Mesh to be focused based on the button. For example, when the "view top" button is clicked, the mesh should be focused from the top. Is there an inbuilt method in three.js to focus a mesh or how can I calculate ...

Implementing Jquery to attach a click event immediately after adding a new row to the table, all

I have an issue where I am adding a new row to my table. Within this row, there is a button that should be clickable and trigger an event. I have come across various solutions, but they all involve using the following code: .on('click', 'bu ...

Operating a React application in the background

Being a novice in the world of deploying front-end code, I have encountered a challenging situation that requires assistance. I am currently working on a React App that needs to be operated as a background process. However, I'm facing some confusion r ...

Performing a periodic sum on an array using Java 8 streams

I am looking to calculate a periodic sum on an array by summing values based on index modulo n. int size=100; double[] doubleArr = new double[size]; for (int i = 0; i < size; i++){ doubleArr[i]=Math.random(); } int n=2; double[] results= new double ...

"Encountering an error while parsing the result of an HTTP request in Node.js

Receiving information from an external api: var requestData = http.get('http:...format=json', function(responseFromApi) { if(responseFromApi.statusCode !== 200){ res.status(400).send(data); return; } responseFromApi.on('data&a ...