Divide the array based on its individual values

I am dealing with an array like the one below:

var aaa = [
  [[value1,value2],[0,0]],
  [[value3,value4],[0,1]],
  [[value5,value6],[1,0]],
  [[value7,value8],[0,2]],
  [[value9,value10],[1,1]],
  [[value11,value12],[2,0]]
];

Now, I want to split this array into multiple arrays based on specific values such as [0,1], [0,2], etc.

This means creating new arrays like:

array1 = [[value1,value2],[value3,value4],[value7,value8]];
array2 = [[value5,value6],[value9,value10]];
array3 = [[value11,value12]];

What is the best approach to achieve this?

Answer №1

Here is a code snippet you can use:

const myArray = [
[['apple','orange'],[0,1]],
[['banana','grape'],[0,2]],
[['kiwi','melon'],[1,0]],
[['pear','strawberry'],[0,3]],
[['blueberry','raspberry'],[1,1]],
[['pineapple','peach'],[2,0]]];

let result = {};

for (let i = 0; i < myArray.length; i += 1) {
    if (!result[myArray[i][1][0]]) {
        result[myArray[i][1][0]] = [];
    }
    result[myArray[i][1][0]].push(myArray[i][0]);
}

You can then access the results like this:

result[0]; //[[apple,orange],[banana,grape],[pear,strawberry]];
result[1]; //[[kiwi,melon],[blueberry,raspberry]];
result[2]; //[[pineapple,peach]];

Answer №2

Consider the following scenario:

[['item1','item2'],[0,1]]

In this instance: 0 indicates in which array the item should be placed. 1 indicates in which position within that array it should be stored.

The provided code accomplishes this task:

var data = [
    [['item1','item2'],[0,1]],
    [['item3','item4'],[0,2]],
    [['item5','item6'],[1,0]],
    [['item7','item8'],[0,3]],
    [['item9','item10'],[1,1]],
    [['item11','item12'],[2,0]]
];

var result_array = new Array();

for (var index in data) {
    if (result_array[data[index][1][0]] == undefined) {
        result_array[data[index][1][0]] = new Array();
    }
    result_array[data[index][1][0]][data[index][1][1]] = data[index][0];
}

Note: This may result in empty cells, as demonstrated by the absence of a [0,0] cell in the example provided.

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

Guide on using Fetch API to send a request to a PHP file using the POST method

Hey everyone, I've recently started delving into the world of PHP and I encountered an issue while attempting to send a post request from my JavaScript file to my PHP file using the Fetch API. Upon making the request in my console, I received the foll ...

Troubleshooting why the second statement is not being triggered by the Vuejs

Incorporating a lambda expression into the methods section of a Vuejs component has been a recent challenge for me. Here's an example: I initiate alertyou() and upon receiving the alert, I click okay. Subsequently, in the Vue developer tools, I notic ...

Updating the content of a div when the mouse hovers over it

Looking for some help here - I have a few divs with paragraphs of text inside. My goal is to change the text in each div when it's being hovered over. I know this can be done using JavaScript (jquery perhaps?), but my coding skills are pretty basic. A ...

Once the PostgreSQL container is stopped with docker-compose down, the previously used port becomes unavailable for use again

Currently, I am involved in a project which utilizes express as the server and postgres as the database to delve into dockerization. The server relies on the database being operational. Initially, when running docker-compose up everything functions correct ...

Saving various data types in a single array

Is there a way to store elements of different types in an array without causing issues? In the example provided, there may be potential problems with fitting a 32-bit integer into an 8-bit array. One solution could be to use a shift operator like < ...

What is the correct way to execute the query "select * from table where indexA >= 'a' order by indexB ASC limit 10" in indexedDB?

As I delve into learning about javascript IndexedDB, I have encountered a challenge in executing complex queries. My goal is to perform a select query like this one: "select * from table where indexA >= 'a' order by indexB ASC limit 10" I a ...

Give a class to the element contained within an anchor tag

One way to add a class to the <a>-tag is through this line of code. $("a[href*='" + location.pathname + "']").addClass("active"); However, I am looking to add the class to an li element inside the <a>-tag. What would be the best ap ...

What is the most effective way to utilize zoom with an Orthographic projection?

I'm attempting to utilize THREE.OrbitControls for zooming in an orthographic projection, but I'm not achieving the desired outcome. I believe it may be possible to adjust the viewSize that is multiplied by left, right, top, and bottom to achieve ...

Issue encountered with @Nuxt.js/Cloudinary plugin for Media Enhancement: "Access to this endpoint is restricted due to insufficient permissions"

I am currently utilizing the @nuxtjs/cloudinary module based on the module guide and a course video. However, I am encountering an error in the response as follows: Status 403, message: You don't have sufficient permissions to access this endpoint&qu ...

The output is: [object of type HTMLSpanElement]

<form> <table> <tr> <td>Distance:</td> <td><input type="number" id="distance" onKeyUp="calculate();">m</td> </tr> <tr> <td>Time:</td> ...

What could be causing my prompt for a username to not work properly as I attempt to develop a system that generates a unique code using the user's initials?

I'm currently working on a script that will be used by the secretaries in our school district to generate unique codes for new students or hires. The code will consist of an 8-digit output, a randomly generated 6-digit number, and the user's init ...

Concealing elements with duplicate attributes using jQuery

Is there a way to hide duplicate elements in a list based on a specific attribute value using jQuery? Here is an example list: <div data-title="big hero 6">title</div> <div data-title="big hero 6">title</div> <div data-title="a ...

When hovering over the background, it will enlarge but the text in front will remain the same size

As the user hovers over the image, the image enlarges. However, there is also some information that needs to be displayed in front of the image. This is my current implementation: .home-about-link { overflow: hidden; width: 100%; } .home-about { ...

Avoiding the loading of textures on the obj model in three.js is essential

Can anyone assist with why the texture is not loading? I attempted to load the texture onto a separate mesh in obj file but it's not working, giving an error. Can someone explain why the material is applied but the texture is not loading? var manage ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

Is it possible to utilize an Angular2 service with the DOM addEventListener?

Issue: I am encountering an problem where the service appears to be empty when trying to call it within an addEventListener. Html: <div id="_file0"> Service: @Injectable() export class FilesService { constructor(private http : Http) { } } Co ...

"Is it possible to rearrange the parent div's position when hovering over a child image with jquery sortable

Can you assist me with a task? I have two text boxes with an equal sign image, and I want the user to be able to move the div only when hovering over the equal sign. This means that the user should be able to drag the div using the equal sign. Can you hel ...

Switch out the words within the input box

My code has the ability to convert words to numbers, however, when I try to paste a text like: three four one one four five six one, the output I receive is: 3411456one If I click on the text input again, the word 'one' changes to '1', ...

Increase numbers with uniform speed using jQuery for each number

I am working on implementing a jQuery script that will visually increase any number from zero to its value using setInterval(). Here is the current solution I have come up with: $('.grow').each(function() { var $el = $(this); va ...

How do I use JavaScript to make each trigger execute a function that only impacts its own child elements?

As I delve into the world of Javascript, I find myself grasping the concepts bit by bit. However, there's one thing that's been puzzling me, something so basic that I can't seem to find a clear answer on. My challenge involves a sidebar wit ...