Split an array of simple data types in JavaScript into separate sections

Is there a way to divide an unordered array of primitive types into specific segments like this:

var array = [102,103,104,201,203,204,303,301,302,405,406,408,101];

=>

newArray = [[101,102,103,104],[201,203,204],[303,301,302],[405,406,408]]

The division of the array is based on the first integer in each element.

The segmentation expression might look something like this:

array[i]/100|0 === j;

where j can be 1,2,3, or 4.

For example.

405/100|0 === 4 // place in array segment starting with 4.

If anyone has ideas on how to efficiently filter this array into sections based on the initial number, please share!

I know about lodash's partition function with collections, but I want the array to only consist of primitive types for speed purposes. Additionally, the partition only splits it into two parts.

Appreciate any help in advance!

Answer №1

Follow these steps to achieve the desired outcome:

var arr = [102,103,104,201,203,204,303,301,302,405,406,408,101],
 result = arr.reduce((res,e) => { var idx = e/100|0;
                                  res[idx-1] = res[idx-1] ? res[idx-1].concat(e) : [e];
                                  return res;
                                },[])
             .map(subarr => subarr.sort((a,b) => a-b));
console.log(result);

Answer №2

An example of utilizing lodash function chaining is shown below:

let numbers = [22, 11, 33, 44, 55, 66, 77, 88];
let newNumbersArray = _(numbers)
  .groupBy((n) => Math.floor(n / 10))
  .values()
  .value();

Answer №3

Array.reduce seems to be utilized here:

let numbers = [24, 35, 46, 51, 73, 84, 98, 102, 107];

numbers.reduce (
  function (result, value) { 
    let firstDigit = +value.toString().slice(0, 1);
    result[firstDigit] && result[firstDigit].push(value) || (result[firstDigit] = [value]);
    return result; 
  }, [])

Answer №4

Do correct me if I'm mistaken here. You're in possession of an array that consists of integers, for example [101, 102, 103, 201, 202, 203], and your objective is to convert it into an array of arrays where each sub-array starts with the same integer, like [[101, 102, 103], [201, 202, 203]].

Now, here's a straightforward solution:

// This object will hold the partitioned array
var newObject = {};

for(var i = 0; i < arr.length; i++) {
  var index = arr[i] / 100;
  if(index in newObj)
    newObj[index].push(arr[i]);
  else
    newObj[index] = [arr[i]];
}

Upon completion of this process, you will obtain an object with properties such as 1, 2, 3, each containing an array of numbers starting from those respective indices.

If you desire an array of arrays instead:

var newArr = [];
$(newObj).each(function() {newArr.push(this)});

Feel free to ask if you have any questions.

Answer №5

Utilizing the grouping feature of lodash:

const numArray = [404,101,102,103,104,201,203,204,303,301,302,405,406,408];

const groupedNums = _.groupBy(numArray, (num) => {return num.toString()[0]});

const modifiedArray = [];
for (let index in groupedNums) {
    modifiedArray.push(groupedNums[index]);
}

Answer №6

To begin, it's important to organize your array by sorting it. There are various ways to do this, but in this instance, I'll demonstrate using quicksort. The time complexity for this operation is O (n * log n).

Keep in mind that everything demonstrated here is done manually without utilizing built-in methods. This allows for a clear understanding of the process rather than relying on pre-existing functions.

We start with an unsorted array:

let unsortedArray = [403, 101, 203, 102, 302, 103, 201, 202, 301, 303, 401, 402];

This is our recursive quicksort function:

let quicksort = arr => {
        if (arr.length < 2) {
            return arr;
    }

    let pivotIndex = rand(0, arr.length),
        pivot = arr[pivotIndex],
        less = [],
        more = [],
        sorted = [];

    for (let i = 0, len = arr.length; i < len; i++) {
        if (pivotIndex !== i) {
            if (arr[i] > pivot) {
                more.push(arr[i]);
            } else {
                less.push(arr[i]);
            }
        }
    }

    return sorted.concat(quicksort(less)).concat([pivot]).concat(quicksort(more));
};

let rand = (min, max) => {
    return Math.floor( Math.random() * (min - max) + max );
};

The function is then applied to the unsorted array:

let sortedArray = quicksort(unsortedArray);

The resulting sorted array is:

[101, 102, 103, 201, 202, 203, 301, 302, 303, 401, 402, 403]

With the array now sorted, we proceed to partition it into groups as follows:

[ [101, 102, 103], [201, 202, 203], [301, 302, 303], [401, 402, 403] ]

Utilizing Redu's solution, here is the partition function implemented:

let partition = arr => { 
    return arr.reduce((prev, curr) => { 
        let remainder = curr % 100;

        if (prev[remainder - 1]) {
            prev[remainder - 1] = prev[remainder - 1].concat(curr);
        } else {
            prev[remainder - 1] = [curr];
        }

        return prev;
    }, []);
};

We then apply the partition function to the sorted array:

let partitionedArray = partition(sortedArray);

Resulting in the grouped array:

[ [101, 102, 103], [201, 202, 203], [301, 302, 303], [401, 402, 403] ]
.

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 preventing the overwriting of a JSON object in a React application

I'm trying to compare two JSON objects and identify the differing values in the second JSON object based on a specific key. My goal is to store these mismatched values in a new JSON object. The current issue I'm facing is that when there are mult ...

Troubleshooting the issue of post-initialization store updates not functioning in AlpineJS

When setting up a store, I initially use: document.addEventListener('alpine:init', () => { Alpine.store('selectedInput', 0) }) However, when attempting to update selectedInput within a function later on, it doesn't reflect th ...

Update the options' values in real-time by passing the result of a PHP function

In my PHP code, I have a string variable ($options) that consists of multiple <option> elements structured as follows: <option class="level-0" value="898">Text 1</option> <option class="level-1" value="33">&nbsp;Text 2</opti ...

Is there a way to transform JSON text into a JSON object?

Similar Question: How do I convert JSON to a JavaScript object? { "data": [ { "name": "JoongBum Lee", "id": "526210623" }, { "name": "\uc774\uc778\uaddc", ...

Attempting to assign a thumbnail image to a file on Google Drive by utilizing JavaScript

I've been working on adding thumbnails to the files that I upload to Google Drive using Javascript. I'm following the instructions outlined at https://developers.google.com/drive/v3/web/file#uploading_thumbnails For my web-safe base64 image, I c ...

Converting and downloading CSV to XLSX directly from the front end using TypeScript and React

After successfully converting a JSON response to CSV format for download using the function below, I am now looking to achieve the same functionality but with xlsx files on the front end. The current function works well for CSV files and handles Japanese ...

Problem with traversing from parent to children elements using jQuery selectors

<form data-v-c4600f50="" novalidate="novalidate" class="v-form"> <div data-v-c4600f50="" class="pr-2" question="Top Secret4"> <div data-v-c4600f50="" f ...

When the mouse leaves, the gauge chart component's size will expand

I have encountered a problem while using the react-gauge-chart library in my react project. Within the project, I have integrated a popover component using material-ui and incorporated the gauge chart component from the library within the popover modal. T ...

Switch out the URL in npm's build process

While developing, I am using a mock REST service but for the public release, I intend to switch to a real backend. Is there a method to update the endpoint URL during the npm build process? ...

Failure to load image logo when refreshing the page

There's something peculiar happening in my App.vue. Imagine I have a route link, let's say it's localhost/tools or any similar route. The logo image will display on this route. Take a look at the image here https://i.stack.imgur.com/6HaXI.p ...

ReactJS with conditional closing tags

Here is a sample json response : {id: 1, name: a} {id: 2, name: b} {id: 3, name: c} {id: 4, name: d} {id: 5, name: e} {id: 6, name: f} I am looking to organize these by pairs in my React component like so : <div className="group-item"> ...

Ways to incorporate sass:math into your vue.config.js file

While using vue-cli with Vue 2.6 and sass 1.49, I encountered errors in the console related to simple division calculations: Deprecation Warning: Using / for division outside of calc() is deprecated and will be removed in Dart Sass 2.0.0. I attempted to ...

There was an issue encountered when trying to call a PHP file within an HTML table using Ajax and data.html

For a small project, I have various news items that need to be included from the "news_all.php" file into table data within the "dashboard.php" file. Due to the predefined root structure restrictions, using include('news.php') is not an option. I ...

Adjust an OnDemandGrid utilizing dstore/Rest output through a POST request instead of a PUT request

I am facing a perplexing issue. I have an OnDemandGrid that is editable, and below it, I have a dstore/Rest collection connected to my backend (using PHP). While I can edit the data in the OnDemandGrid, I am unable to save it properly. When it reaches the ...

The client using socket.io is receiving events for "double plus one"

While experimenting with socketio, I encountered a bug that others are experiencing as well but I haven't been able to find a valid solution. This is the server-side code: const app = require('express')(); const server = require('http& ...

How can I pass the content of a pug input element to a JavaScript function?

Attempting to manipulate data on a database using HTML buttons and encountering an issue when trying to insert data. The setup involves a Pug page called by Node Express, which generally functions well until the insertion process. Here is a snippet from th ...

Establishing flow types and generating unchangeable records

Looking to integrate Flow with Immutable.js Records, I've set up my record like this: const MyRecord = new Immutable.Record({id: undefined}) Now when I create records using new MyRecord({id: 1}), Flow gives me an error: constructor call Construct ...

What is the best way to apply a CSS class to my anchor tag using JavaScript?

I have a good grasp of using JavaScript to insert an anchor element into my webpage. For instance, var userName_a = document.createElement('a'); However, I am interested in adding a style name to that same element as well. I attempted the follo ...

What is the best way to eliminate a vertical line from the canvas in react-chartjs-2?

Can someone please lend me a hand? I've been working on a project in React JS that involves using react-chartjs-2 to display charts. I'm trying to incorporate a range slider for the chart to manipulate values on the x-axis, as well as two vertic ...

Prevent modal from closing when tapping outside of it

I'm currently facing a challenge in creating a popup modal that cannot be closed by clicking outside the modal window. I have explored various solutions involving backdrops but none of them seem to be effective. Any assistance would be greatly appreci ...