Dividing a collection of items of varying length into a single array

I have an object with multiple arrays of data, and I want to filter out the 0 values and sort them in descending order.

My current solution extracts each value from the objects and puts it into a separate array. However, I am seeking a more efficient and concise approach. Any suggestions would be greatly appreciated!

const arr = {
  "rows": [{
    "value": "demo value 1",
    "data": [15, 45, 0, 0]
  }, {
    "value": "demo value 2",
    "data": [11, 87, 0, 0]
  }, {
    "value": "demo value 3",
    "data": [8, 113, 0, 0]
  }, {
    "value": "demo value 4",
    "data": [7, 26, 0, 2]
  }, {
    "value": "demo value 5",
    "data": [7, 3, 0, 0]
  }, {
    "value": "demo value 6",
    "data": [6, 17, 0, 1]
  }]
};

let newArr = [];
let newArr2 = [];
let newArr3 = [];
let newArr4 = [];

for (i = 0; i < arr.rows.length; i++) {
  if (arr.rows[i].data[0] != 0)
    newArr.push({
      value: arr.rows[i].value,
      data: arr.rows[i].data[0]
    })
  if (arr.rows[i].data[1] != 0)
    newArr2.push({
      value: arr.rows[i].value,
      data: arr.rows[i].data[1]
    })
  if (arr.rows[i].data[2] != 0)
    newArr3.push({
      value: arr.rows[i].value,
      data: arr.rows[i].data[2]
    })
  if (arr.rows[i].data[3] != 0)
    newArr4.push({
      value: arr.rows[i].value,
      data: arr.rows[i].data[3]
    })
  /// ... and so on
}

console.log(newArr)
console.log(newArr2)
console.log(newArr3)
console.log(newArr4)

EDIT:

Expected result:

[
  [
    {
      "value": "demo value 1",
      "data": 15
    },
    {
      "value": "demo value 2",
      "data": 11
    },
    {
      "value": "demo value 3",
      "data": 8
    },
    {
      "value": "demo value 4",
      "data": 7
    },
    {
      "value": "demo value 5",
      "data": 7
    },
    {
      "value": "demo value 6",
      "data": 6
    }
  ],
  [
    {
      "value": "demo value 3",
      "data": 113
    },
    {
      "value": "demo value 2",
      "data": 87
    },
    {
      "value": "demo value 1",
      "data": 45
    },
    {
      "value": "demo value 4",
      "data": 26
    },
    {
      "value": "demo value 6",
      "data": 17
    },
    {
      "value": "demo value 5",
      "data": 3
    }
  ],
  [],
  [
    {
      "value": "demo value 4",
      "data": 2
    },
    {
      "value": "demo value 6",
      "data": 1
    }
  ]
]

Answer №1

It's a bit tricky to say if this is exactly what you're looking for since there isn't a specified "expected format," but following these steps might point you in the right direction

let fresh_arrays = [];

for (let x = 0; x < collection.rows.length; x++) {
    let current_row = collection.rows[x];
    for (let y = 0; y < current_row.data.length; y++) {
        let current_data = current_row.data[y];

        if(current_data === 0){
            continue;
        }

        if(fresh_arrays[y] === undefined){
            fresh_arrays[y] = [];
        }

        fresh_arrays[y].push({
            value: current_row.value,
            data : current_data,
        });
    }

}

console.log(fresh_arrays);

IMPORTANT: If all values at an index are 0 (or the index doesn't exist), no new array will be created at that index

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

Retrieve the size of an element without having to wait for the browser to "recalculate style"

I am currently focused on optimizing the performance of some code that heavily relies on graphics. One of the main issues I am encountering is the delay in obtaining the dimensions of a specific div element. Most of the time, this process runs smoothly, bu ...

A Guide to Updating Text within an HTML Document

I've encountered an issue while working on my node.js project: Is there a way to dynamically update text in an HTML file? Within the HTML file, I have the following lines of code: <div class="col-md-12 col-xl-12 offset-xl-5"> ...

adding a new object to a list in JavaScript using the last key value

Need help with appending a new object list within a nested last key value in JavaScript. Here is my initial input: var list = [12,13,14,15] Desired output: list = [{first : 12, sec : 13},{first:13, sec:14},{first:14, sec:15}] ...

Create a unique shader in Three.js that remains unaffected by the fog effect

I have implemented a custom shader to add glow to a sphere on my scene. However, I noticed that the fog in the scene affects the sphere but not the glow. When I zoom out, the sphere disappears but the glow remains visible. Is there a way to make the fog ...

Need help with writing code in Angular for setting intervals and clearing intervals?

I am working on the functionality to display a loader gif and data accordingly in Angular. I have tried using plain JavaScript setInterval code but it doesn't work for $scope.showLoader=true and $scope.showResult=true. The console.log('found the ...

Present timestamp using the date API format of YouTube

I'm working with the YouTube API, which provides uploaded and updated times in this format: 2013-05-13T13:12:42.000Z (ISO 8601). How can I use Javascript or jQuery to get the relative time? Despite trying various sources, the date formatting seems to ...

The Intersection Observer encountered an issue as it was unable to access the property 'current' since it was undefined

My current project involves the implementation of IntersectionObserver, but I am facing an issue where I receive the error message Cannot read property 'current' of undefined. Can anyone help me identify what might be causing this problem? useOn ...

Using dynamic imports in Next.js allows us to efficiently load modules based on variables defining the path

When utilizing dynamic import in Next.js, I am encountering an issue. The component renders successfully when the path is used directly, but fails to render when the path is accessed from a variable. const faq = dynamic(() => import('../faq/faq&apo ...

Creating transparent circles with Javascript on an HTML5 canvas

Currently, I am working on a function that allows the user to draw multiple circles on canvas by starting with a mousedown event at center (x,y) and dragging the mouse to specify the radius of the circle. The requirement is to have transparent circles so t ...

Ensure there is a gap between each object when they are arranged in a

Is there a way to customize the layout of elements in the ratings view so that there is automatic spacing between them? I considered using text (white spaces) for this purpose, but it seems like an inefficient solution. Are there any other alternatives to ...

Guidelines on populating a Vue array with data fetched from an Axios request

The v-breadcrumbs component is used to display data from the breadcrumbs array, which works seamlessly with static data. <v-row> <!-- Breadcrumbs --> <v-col class="d-flex"> <v-breadcrumbs :items="breadcrumbs"></v ...

Find a Mongoose query that retrieves items where X exists in both arrays, while Y only exists in one array

I am currently constructing a filtering mechanism and have run into a roadblock. It's worth noting that this code is for demonstration purposes only and does not belong to the actual project, but the core idea remains consistent. I have altered the na ...

Exploring the functionality differences between mouse wheel tilt and scroll in JavaScript with scrollTop

Did you know that some computer mice come equipped with a scroll wheel that can tilt both left and right? This feature allows users to navigate through Google's piano roll app, which can be accessed here (source code available here). I am working to ...

Ways to gradually adjust the height of a Div element

Is there a way to smoothly reveal a Div when scrolling down and clicking on a button? Currently, it seems to just appear quickly without any sliding effect. What could be causing this issue? function showstuff(inquiryForm){ document.getElementById(inq ...

Save data using Django forms upon clicking a button

Currently in the process of learning Django, I decided to create a small app that involves creating a form for VoteType and voting candidates on a single page. I have successfully implemented a feature where users can add multiple candidate fields as neede ...

An issue with the AngularJS [$parse:syntax] error has been identified when using specific data in the

I encountered an issue when attempting to create an AngularJS ui-grid table with data that includes a '(' and then whitespace before the closing ')' within a string. This resulted in an AngularJS error message: Syntax Error: Token &a ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

What is the best way to incorporate an expression into a package.json file?

Query: Is there a way to automatically increase the version in a script message? I need my release message to always be one version higher than the previous. Aim: For example, if I have version **0.1.2**, I would like to update my commit message to 0.1.3 ...

Transferring binary data from C# to Node.js for deserialization

I am facing a challenge where I have a byte array created in C# from an object type, which is then sent over the socket protocol to a Node.js app. However, I am unable to deserialize the data into a readable object. Can anyone suggest a way to decode this ...

Utilizing AngularJS to connect a dynamic result array to a table with varying layouts

I am struggling to bind a dynamic array result with a table using Angular JS in a different layout. Despite multiple attempts, I have not been successful in achieving the desired outcome. Any help or guidance would be greatly appreciated. var arr = [ ...