Generate a main array containing nested arrays made up of individual values

Challenge:

I am facing an issue where I have a series of numerical values separated by commas that I need to convert into an array. Each pair of values should be nested within the main array to represent drawing vertices.

How can I tackle this challenge effectively?

Data Input:

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

The desired output should look like this:

Expected Output:

var V_array = [[24,13],[47,20],[33,9],[68,18],[99,14],[150,33],[33,33],[34,15],[91,10]];

Answer №1

If you are looking to manipulate an array by splitting on every second comma in JavaScript, consider using the approach suggested here. By splitting the string and converting values to numbers, you can map the splitted pairs effectively.

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10",
    result = vertices.match(/[^,]+,[^,]+/g).map(s => s.split(',').map(Number));

console.log(result);

Answer №2

To check for the modulus of each index in a splitted-string, you can utilize the reduce function within your code structure.

let str = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

let result = str.split(','.reduce((a, s, i) => {
  a.curr.push(Number(s));
  if ((i + 1) % 2 === 0) {
    a.arr.push(a.curr);
    a.curr = [];
  }
  
  return a;
}, {arr: [], curr: []}).arr;

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

To convert a string into an array and utilize the reduce method, consider the following code snippet:

const vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

const numbers = vertices.split(',').map(Number)

const res = numbers
  .reduce((acc, number, index, srcArray) => {
    if (index % 2) {
      return acc
    }

    return [
      ...acc,
      [ number, srcArray[index + 1] ],
    ]
  }, [])

console.log(res)

Answer №4

Sharing my thoughts :) [updated]

let
  sequence     = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10",
  pairArray    = [],
  tripletArray = [];

JSON.parse(`[${sequence}]`).forEach((element,index)=>{pairArray.push( (index%2)?[pairArray.pop(),element]:element)})

console.log ( 'pair:', JSON.stringify(pairArray) )


// bonus => extending the concept to triplets :

JSON.parse(`[${sequence}]`).forEach((element,index)=>{
  if      ( (index%3)===2 )  tripletArray.push( [tripletArray.shift(),tripletArray.pop(),element] )
  else if ( (index%3)===0 )  tripletArray.unshift(element)
  else                      tripletArray.push(element)
})

console.log ( 'triplet:', JSON.stringify(tripletArray)  )

Answer №5

To achieve this, utilize the exec function along with JSON.parse.

var coordinates = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

var array1;
var reg = /[^,]+,[^,]+/g
let result = []

while((array1 = reg.exec(coordinates))!== null){
  result.push(JSON.parse(`[${array1[0]}]`))
}

console.log(result)

Answer №6

Divide the string by commas and utilize Array.reduce to organize the pairs into a new 2-dimensional array:

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";
const pair = vertices.split(",").reduce((acc, ele, idx, arr) => {
  if(idx === 0  || idx%2 === 0) {acc.push([+ele, +arr[idx + 1]]);}
  return acc;
}, []);
console.log(pair);

The same outcome can be achieved using Array.map, where for odd indexes, skip the element and eliminate any undefined elements:

var vertices = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";
const pair = vertices.split(",").map((ele, idx, arr) => (idx === 0 || idx%2 === 0) ? [+ele, +arr[idx + 1]] : undefined).filter(e => e);
console.log(pair);

Answer №7

Just my thoughts :)

(special thanks to Coding Guru for introducing the concept of using JSON.parse )

let nums = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

let parsedNums = JSON.parse(`[${nums}]`).reduce((result, current, index) => {
  if (index===1) return [[result,current]];

  if (index%2 === 0) {
    result.push(current);
  } else {
    let prev = result.pop();
    result.push([prev, current]);
  }

  return result;
});

console.log(parsedNums);

Answer №8

Here is my solution.

var points = "24,13,47,20,33,9,68,18,99,14,150,33,33,33,34,15,91,10";

points = points.split(",");

function splitIntoPairs (arr, length) {
  var newArr = [];
  while(arr.length > 0) {
  newArr.push(arr.splice(0,length));
  } 
  return newArr;
}

const result = splitIntoPairs(points, 2);

console.log('result', result);

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

Achieve a new line break when the user hits the "Enter" key using HTML and JavaScript

I'm in the process of developing a Chrome Extension that allows users to create a to-do list. My goal is to enable users to submit their task by pressing the "Enter" key, which should move the task to the next line after submission. I am currently fac ...

Having difficulty showcasing API call results in a Vue.js component

I am currently experimenting with Vue.js in an attempt to showcase results from a Wikipedia API call within a component using the v-for directive. However, I seem to be encountering some backend issues that I cannot pinpoint. To access the jsFiddle link, ...

Storing MySql values as Multidimensional Array with PHP: A Comprehensive Guide

Below is a representation of my database table. <table border='1'><th>Id</th><th>FirstName</th><th>last Name</th><tr><td>1</td><td>Tom</td><td>T</td></tr>& ...

Transforming Unix timestamps into readable dates for each entry in a column

I have a process that can be easily replicated numerous times to generate the data I need. =ArrayFormula(if(A2="","",(A2/1000/60/60/24+date(1970,1,1)))) However, this formula breaks whenever a new row is inserted or deleted. To resolv ...

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

Determine the associated value for a given key within a TypeScript object

I have a structure like this: type newsItem = { img: string; slug: newsSlug; text: newsText; }; derived from an enum like this: export const newsEnum = { interesting: "Interesting", regions: "Regions", contradictory: " ...

What is the best way to incorporate an npm module in a django-admin widget without the need to install node?

Background I am working on a Django app and need to create an admin widget. The widget will display text in a unique terminal-style format to show forwarded logs from an analytics process managed by Django (using the django-twined extension). To achieve ...

Determine the data type of a property within a JavaScript object

I am currently working with a javascript object that looks like this: venue = { id: 0, name: '', venueimage_set: [ { imageurl: '', }, ]... At a later point in my code, I need to modify the object ...

Converting HTML table text to JSON data using vanilla JavaScript (without any external libraries like Selenium)

As a newcomer to programming and Javascript, my goal is to use Selenium Webdriver in Visual Code to extract HTML table content from a webpage and convert it into JSON data. I've managed to retrieve the table data, but I'm struggling with the conv ...

How to extract specific elements from arrays in PHP

After inputting values into a PHP file using text boxes and storing them in an array with a common name attribute, I am facing an issue where not all values from the array are being used. What is the best way to access individual elements? <td><i ...

The catch-all route handler is triggered following a response being sent by a designated route handler

Currently, I am facing a peculiar issue with the routing on my Express-based server while trying to implement authentication. Here's a snippet of code that highlights the problem: app.get('/', function (req, res) { console.log('thi ...

A guide on transforming a string-formatted array into a standard array

Looking to convert the array a="(1,2),(2,3),(3,4)" into a normal list format in Python such as a=[(1,2),(2,3),(3,4)], for easy element access using an index. Any ideas on how to achieve this? ...

Guide to customizing the default scrollbar colors in Nextjs

When browsing websites like tailwindcss.com or https://developer.mozilla.org/ in Chrome and Firefox, you may have noticed that they utilize the default scrollbar style but allow users to change its colors through a dark/light mode button. The appearance of ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Accessing JavaScript elements from PHP code

Is it possible to recognize JavaScript elements if they are nested within PHP tags? For example: <?php $username = "maniacal"; echo "<p class='welcome' id='greeting'>Hi, Welcome to the site!!</p>" ?> That's ...

AngularJS : "Executing successive promises" with additional functions interspersed

Recently, I encountered a challenge in my Angular project. As a newcomer to Angular, I was tasked with modifying a directive that handles forms to ensure the submit button is disabled during processing and then enabled again once all operations are complet ...

Performing a bulk upsert operation by utilizing the $in operator in the update criteria

As I create a procedure to handle an array of strings like var mywords = ["cat", "dog", "fish"] and insert them into the 'words' collection in MongoDb, I aim to keep track of the insertion count for each word. Some words may already exist in t ...

Experience the convenience of uploading photos using jQuery Dialog on your ASP.NET MVC website

I am in the process of developing an ASP.NET MVC 3 application and encountering an issue with using a jQuery Dialog to upload a photo. Despite my code implementation, the HttpPostedFileBase object within my model (representing the file to be uploaded) cons ...

Establishing a connection between JavaScript and MySQL within an HTML document

Recently, I started using node.js's node-mysql driver for MySQL and decided to write this piece of code: var mysql = require("mysql"); var connection = mysql.createConnection({ host : "localhost", user : "root", ...

Struggling with the navbar-toggler in Bootstrap 4 Beta 2?

As part of my Bootstrap practice, I have implemented a navbar on my webpage. However, I am facing issues with the nav-bar toggler not working for small screens and the icon navbar-toggler-icon not appearing. Below is my current navbar code: <nav class ...