Using JavaScript's `Map` function instead of a traditional `for`

My dataset consists of a csv file containing 5000 rows, with each row having thirty fields representing measurements of different chemical elements.

I aim to parse and visualize this data using D3js. Upon reading the file, I obtain an array of length 5000 where each element is an object holding measurements of various chemical elements. For example, measurements[5].Aluminium provides the concentration of Aluminium at the fifth measurement.

Instead of individual values, I wish to organize the data into arrays for each element. While achievable through a for-loop, I want to experiment with the map function.

Aluminium = measurements.map(function(row){
    return row.Aluminium;
});

The above code successfully creates an array for one element, but I desire a more flexible approach by passing the element name as a parameter.

function selectElement(elementname){
      measurements.map(function(row){
          return row.elementname;
      });
};

Aluminium = selectElement('Aluminium');
Iron = selectElement('Iron');

However, implementing this change has proven challenging, leaving me at a roadblock in my progress.

Answer №1

By utilizing Javascript, you have the ability to access children properties by specifying the key within square brackets. So instead of obj.key, you can use obj['key']

With this approach, the selectElement function can be modified as shown below:

function selectElement(elementname){
      measurements.map(function(row){
          return row[elementname];
      });
};

It is understood that elementname is a string which acts as a selector for the row object

Answer №2

row.elementname searches for a key containing the value "elementname". Using dot notation alone does not perform any evaluations. Remember to

function findElement(dataSet, elementname){
      return dataSet.map(function(row){
          return row[elementname];
      });
};

Gold = findElement(dataSet, 'Gold');
Silver = findElement(dataSet, 'Silver');

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

Utilizing PHP to create an interactive website

As a novice PHP developer, I took to Google in search of tutorials on creating dynamic PHP websites. What I found was that many tutorials used the $_GET variable to manipulate URLs and make them appear like this: example.com/?page=home example.com/?page= ...

Error: Attempting to access a property called 'name' on an undefined variable leads to a TypeError

I am a beginner with MongodB and nodejs. I have successfully implemented the GET method, which returns an empty array. However, when I tried to use POST in Postman for "categories," I encountered this error message: ExpressJS categories route app.js Err ...

Click on the navigation bar buttons to toggle between different divs and display multiple information boxes simultaneously

Here is the current code snippet... $("#contact").click(function() { if ( $( "#contact_div" ).length ) { $("#contact_div").remove(); } else { var html='<div id="contact_div" class="contact-info"><p>Contact info</p&g ...

Changes in a deep copy of an object in a child component are directly reflected in the parent object in VueJS

Let's begin by discussing the layout. I have a page dedicated to showcasing information about a specific company, with a component Classification.vue. This component displays categories of labels and the actual labels assigned to the current company. ...

Identify when an ajax request is completed in order to trigger a subsequent ajax request

Within my project, I am faced with a challenge involving select option groups that dynamically load ajax data based on previous selections. The issue arises when I attempt to replicate this functionality for another select option group. Here is the scenar ...

The Vue.js error message "Unable to access property 'array_name' as it is undefined" indicates an issue with

I'm currently working on fetching data using Axios requests and storing it in an array. Below is the code I have been using: props: [ 'products', ], data: function () { return { algolia: '', pro ...

Switching the markLine in vega lite to a markBar causes it to lose its sorting arrangement

I have created the following data visualization: data = [{"student_name": "student 0", "e": "100.15", "d": "127.81"}, {"student_name": "student 1", "e": "100.30", "d": "189.94"}, {"student_name": "student 2", "e": "100.15", "d": "105.33"}, {"student_nam ...

Adaptable design tailored for smartphones

When it comes to developing mobile websites for various platforms such as iPhone 3 and 4, Android, Blackberry Torch, etc., I usually find myself needing to slice images based on the specific platform. The challenge arises from constantly having to slice im ...

Issue with jQuery's JSON data not being properly transmitted to CodeIgniter (`

Based on my observation, the script provided below seems to be functioning properly: <script type="text/javascript" language="javascript"> $(document).ready(function() { $('#add').bind('keypress', function(e) { if(e.k ...

You will still find the information added with JQuery append() even after performing a hard refresh

After making an Ajax call using JQuery and appending the returned information to a div with div.append(), I encountered a strange issue. Despite trying multiple hard refreshes in various browsers, the appended information from the previous call remained vi ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...

Having trouble with my AJAX request and can't figure out why. Anyone available to take a look and help out?

I have successfully implemented this AJAX script on various pages in the past without any issues. <script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript" src="jquery.validate.min.js"></script& ...

What are the reasons for validation failure when it is moved into a method?

I am currently in the process of developing a validation function in JavaScript. However, when I extracted the logic into a private method, my validation started failing and I can't seem to figure out why. Here is my HTML definition: <input type= ...

I am facing an issue with Angular where the $http.get method is

It seems like there must be a small oversight causing this apparently simple problem. I have a function that interacts with the Spotify API to search for an artist. I know that by accessing the corresponding route using a standard URL, a result is returne ...

Setting up a Node.js application with Nginx on DigitalOcean

While running my application on a DigitalOcean droplet using nginx, I encountered a peculiar issue. The app runs perfectly fine with http, but when switching to https, nginx throws a 502 BAD GATEWAY error. Despite trying various DigitalOcean guides and sco ...

Using JavaScript, HTML, and CSS to select slices of a donut pie chart created with SVG

I have successfully implemented CSS hover effects and can manipulate the HTML to use the .active class. However, I am facing difficulties in making my pie slices switch to the active state upon click. Moreover, once this is resolved, I aim to enable select ...

Effect of Active or Focus on the HTML <ul> element

Check out this example of a UL tag: <ul style="list-style-type:none; padding:5px ; border:solid 1px #666666;"> <li>I am waiting </li> <li>I am waiting </li> <li>I am waiting </li> <li>I am wa ...

jsTree unable to locate node using the provided ID

Implementing the jsTree on the webpage is not a problem for me. I have experimented with numerous suggestions from different sources. $('#myTree').jstree({ .... }) .on('loaded.jstree', function (e, dta) { var t = $('#myTree&a ...

Two ng-click events are triggered within a nested ng-click

I am facing an issue with using the ng-click within a nested list under another list that also has a ng-click event. Here is my code snippet: <ul> <li ng-repeat="facet in node.Facets" ng-click="updateNav(facet.Action)" ng-cloak & ...

Unusual behavior observed in AngularJs local variables

This code snippet is from the controller: cat1=[]; $.getJSON('categories/1/', function(data) { cat1 = data; //this returns a JSON object }); //cat2..4 are also JSONs $scope.pictures=[cat1,cat2,cat3,cat4,cat5]; The issue here seems to be th ...