Filtering data in JavaScript arrays involves selecting certain elements based on

I have successfully implemented an array filter using JavaScript and lodash. I am now looking to combine arrays of arrays into a single array. Can anyone provide guidance on how to achieve this?

Sample Input

const inputData = [
  [
    { 'Tempe(C)': 12 },
    { 'Tempe(C)': 13 },
    { 'Tempe(C)': 14 },
    { 'Tempe(C)': 15 }
  ],
  [
    { 'Tempe(C)': 22 },
    { 'Tempe(C)': 23 },
    { 'Tempe(C)': 24 },
    { 'Tempe(C)': 25 }
  ],
  [
    { 'Tempe(C)': 32 },
    { 'Tempe(C)': 33 },
    { 'Tempe(C)': 34 },
    { 'Tempe(C)': 35 }
  ],
];

Desired Output Structure

const outputData = [
  [12, 13, 14, 15],
  [22, 23, 24, 25],
  [32, 33, 34, 35],      
];

Answer №1

You may want to consider utilizing Object.values along with map

const inputData = [[{"Tempe(C)":12},{"Tempe(C)":13},{"Tempe(C)":14},{"Tempe(C)":15}],[{"Tempe(C)":22},{"Tempe(C)":23},{"Tempe(C)":24},{"Tempe(C)":25}],[{"Tempe(C)":32},{"Tempe(C)":33},{"Tempe(C)":34},{"Tempe(C)":35}]];
const output = inputData.map(arr => arr.map(a => Object.values(a)[0]))
console.log(output)

If your browser supports flat:

const inputData = [[{"Tempe(C)":12},{"Tempe(C)":13},{"Tempe(C)":14},{"Tempe(C)":15}],[{"Tempe(C)":22},{"Tempe(C)":23},{"Tempe(C)":24},{"Tempe(C)":25}],[{"Tempe(C)":32},{"Tempe(C)":33},{"Tempe(C)":34},{"Tempe(C)":35}]]
const output = inputData.map(arr => arr.map(Object.values).flat())

console.log(output)

(This method is applicable for any key. However, if the key is consistently Tempe(C), @eol's solution would be more efficient)

Answer №2

In the case where Tempe(C) always serves as the key for the values, you can easily achieve this by:

const dataset=[[{"Tempe(C)":12},{"Tempe(C)":13},{"Tempe(C)":14},{"Tempe(C)":15}],[{"Tempe(C)":22},{"Tempe(C)":23},{"Tempe(C)":24},{"Tempe(C)":25}],[{"Tempe(C)":32},{"Tempe(C)":33},{"Tempe(C)":34},{"Tempe(C)":35}]];

const result = dataset.map(dataArr => dataArr.map(entry => entry['Tempe(C)']));

console.log(result)

Answer №3

Hey there, Ragu! Here are the steps to achieve the desired outcome:

var data = [
    [
      { 'Temp(C)': 12 },
      { 'Temp(C)': 13 },
      { 'Temp(C)': 14 },
      { 'Temp(C)': 15 }
    ],
    [
      { 'Temp(C)': 22 },
      { 'Temp(C)': 23 },
      { 'Temp(C)': 24 },
      { 'Temp(C)': 25 }
    ],
    [
      { 'Temp(C)': 32 },
      { 'Temp(C)': 33 },
      { 'Temp(C)': 34 },
      { 'Temp(C)': 35 }
    ]
];

var newStructure = [];

for(var x in data){
    newStructure[x] = [];
    for(var y in data[x]){
        newStructure[x][y] = data[x][y]["Temp(C)"];
    }
}


Answer №4

When using lodash, you can achieve the desired result by nesting _.map() functions:

const data = [[{"Tempe(C)":12},{"Tempe(C)":13},{"Tempe(C)":14},{"Tempe(C)":15}],[{"Tempe(C)":22},{"Tempe(C)":23},{"Tempe(C)":24},{"Tempe(C)":25}],[{"Tempe(C)":32},{"Tempe(C)":33},{"Tempe(C)":34},{"Tempe(C)":35}]]

const result =  _.map(data, o => _.map(o, 'Tempe(C)'))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

To achieve the same outcome using lodash/fp:

const fn = _.map(_.map('Tempe(C)'))

const data = [[{"Tempe(C)":12},{"Tempe(C)":13},{"Tempe(C)":14},{"Tempe(C)":15}],[{"Tempe(C)":22},{"Tempe(C)":23},{"Tempe(C)":24},{"Tempe(C)":25}],[{"Tempe(C)":32},{"Tempe(C)":33},{"Tempe(C)":34},{"Tempe(C)":35}]]

const result = fn(data)

console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

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

Converting Typescript objects containing arrays into a single array

Looking for some assistance with this problem :) I am trying to convert the object into an array with the following expected result: result = [ { id: 'test-1', message: 'test#1.1' }, { id: 'test-1', mess ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Attempting to construct a .csv file in PHP using an array

I need help converting the array below into a .csv file format, where the questions are placed in the first row, corresponding answers in the second row, and a Timestamp with the current time at the beginning. This is my attempt: <?php $qna = [ ...

Locate different elements within an array?

How can I locate the initial instance of one of multiple values within an array? $sentence = array(I, want, to, go, to, the, market); if(in_array(array('swim','fly','go'), $sentence)) { // The expected result is KEY = 3 s ...

jQuery: What's the Difference Between Triggering a Click and Calling a Function?

Imagine having certain actions assigned to a link using .click or .live, and wanting to repeat the same action later without duplicating code. What would be the right approach and why? Option 1: $('#link').click(function(){ //do stuff }); //c ...

CSS linking causing pages to crumble

Out of nowhere, while working on my project today, my page suddenly collapsed. It was a frustrating sight to see. Immediately, I went back to Dreamweaver and used cmd+z to undo a few steps, but there was no visible issue. Despite this, my page continued t ...

Basic question regarding ArrayLists

I'm faced with the following scenario: public class User { public User(String nickname, String ipAddress) { nickname = nickname.toLowerCase(); System.out.println(nickname + " " + ipAddress); } } Additionally, there is anot ...

The event listener continues to throw an error when attempting to play audio

I'm encountering an issue with triggering audio in my window's load listener function. var audio = new Audio(); audio.src = "assets/silence.mp3"; audio.load(); document.getElementById("body").addEventListener( 'touchstart', functio ...

Transforming a value greater than 255 into a byte data type

Although I have a good understanding of bytes and variable declaration to optimize processing space, I find myself struggling with a current issue and would appreciate some guidance. My experience with byte manipulation is limited. I have been tasked with ...

Duplicate a JSON file and then combine it with a dictionary before adding it to a new JSON file

I currently have an existing JSON file, a new JSON file that needs to be created, and an existing Python dictionary. My goal is to transfer the data from the existing JSON file to the new JSON file, and then add my dictionary to the new JSON file. mydict ...

Is there an issue with importing the JSON Dictionary in .txt file because it contains a value of None type?

I'm currently working on a project that involves utilizing an API, and I've run into issues when trying to write/read the JSON response as a dictionary in a .txt file. It seems like the error is related to the formatting of the dictionary, with v ...

Can you provide guidance on how to pass the selected value from a select option to an onchange function using Vue.js methods?

I'm facing an issue with passing the selected option value id from a select option to an onchange function in my methods. My goal is to store the selected value in the v-model "choosed" every time the user changes the select option, and then pass that ...

What is the best way to modify my if statement to avoid output duplication in my outfile?

When testing for a key, I either do a json.dump if it's present or add it if it's not. Additionally, I check for two other keys and add them if they are absent. I have nested these secondary tests. The issue with the current code is that if the ...

React, Axios, and the PokeAPI are like a team of explorers navigating an

Trying to enhance my React abilities, I decided to follow this tutorial on creating a list of names using PokeAPI. However, I hit a roadblock at 11.35 into the tutorial while implementing the provided code snippets in both App.js and PokemonList.js: fu ...

Ways to control the number of boxes that are checked

I am currently working on a script to restrict the number of checkboxes that can be checked, but I am encountering an issue where the script is disabling all checkboxes on the page. Is there a way to only disable a specific checkbox within a certain div? ...

Integrate updated information regarding a particular node within the tree

I have an array structured with data and I require to add additional data to node X. The specific location of the node X is determined by its path in another array ($path). $data = [ 183013 => [ 183014 => [ 183018, ...

Avoid refreshing the page when adding an item to the cart

I am in the process of creating a online shopping cart and I'm looking for ways to avoid the page from reloading when adding a product to the cart. At the moment, my approach involves using the GET method to add products to the cart. <a href="car ...

Is there a way to verify the location of an element?

Currently, I am attempting to monitor the position of the 'car'. When the car reaches a top offset of 200px, I would like to apply a specific property to the 'phone' element. The concept is that as you scroll down, the car will move, an ...

Is there a way to trigger a function with the onclick event in NextJs?

Working on my NestJS project, I am still a beginner in the field. My current task involves creating a web application that displays a leaflet map with clickable tiles. Each tile should have a button that triggers a specific function when clicked. However, ...

Guide to serializing and deserializing an ArrayList, including properties of an Object datatype

Is there a way to maintain the object types during the deserialization of a json object? I've noticed that the ArrayList is lost and ends up as an object array, while the rectangle is completely gone. Edit: Unfortunately, I am unable to adjust the ob ...