Is multi dimensional array what I am looking for? - javascript

It will seems basic stuff for most of you guys but I'm stuck on this problem:
So I have 3 categories of fields like this:
-Category 1 = [field1, field2, field3.. etc]
-Category 2 = [field1, field2, field3.. etc]
-Category 3 = [field1, field2, field3.. etc]
And on top of that, I have others elements which has all of those categories but not all fields like this:
Element 1 = Category 1[field3, field2], Category2[Field4], Category3[field1, field5, field2]
How am I supposed to organize those data in javascript (I am using Jquery if it can help)?

Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does NOT support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
You may use objects instead:
{
"Element1": {
"Category1": [
"field3",
"field2"
],
"Category2": [
"field4"
],
"Category3": [
"field1",
"field5",
"field2"
]
}
}
You can take a look at MDN is you are a complete beginner to JavaScript and it's data types.
Eloquent Javascript might help too in getting the basics of javascript.

It depends on what you are trying to do with the data but one way could be:
var category1 = ['field1', 'field2', ... ];
var element1 = {
category1: ['field3', 'field2'],
...
}

Related

Create Json with specific structure from two different arrays in javascript

I've already tried to find a solution on stack, but I didn't found a possible reply, so I decided to open a topic to ask:
Let's say we have 2 arrays: one containing "keys" and another one containing "values"
Example:
keys = [CO2, Blood, General, AnotherKey, ... ]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[... [
I have to create a Json with a specific structure like:
[{
name: 'CO2',
data: [2,5,4,6]
}, {
name: 'Blood',
data: [4,5,6]
}, {
name: 'General',
data: [1,3,34.5,43.4]
}, {
...
},
}]
I've tried to make some test bymyself, like concatenate strings and then encode it as json, but I don't think is the correct path to follow and a good implementation of it ... I've also take a look on JSON.PARSE, JSON.stringify, but I never arrived at good solution so... I am asking if someone know the correct way to implements it!
EDIT:
In reality, i didn't find a solution since "name" and "data" are no strings but object
Here's one way to get your desired output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = keys.map((x, i) => {
return {"name": x, "data": values[i]}
})
console.log(output)
However, since you're literally constructing key/value pairs, you should consider whether an object might be a better data format to output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = {}
for (let i=0; i<keys.length; i++) {
output[keys[i]] = values[i]
}
console.log(output)
With this data structure you can easily get the data for any keyword (e.g. output.CO2). With your array structure you would need to iterate over the array every time you wanted to find something in it.
(Note: The reason you weren't getting anywhere useful by searching for JSON methods is that nothing in your question has anything to do with JSON; you're just trying to transform some data from one format to another. JSON is a string representation of a data object.)

Converting a string to a list and seperate each element

So I have a use case in which I enter indexes and descriptions which belong to a round. I created a JS function that allows me to enter these indexes and descriptions. When I strip the data from the post request I get the following data:
['0,This is a testround', '1,This is a new testround']
I want to split this data so that I can seperate the 0 in an index variable and the following description "This is a testround" in a description variable. Please note that the description can only contain comma's. The indexes are not always corresponding with the indexes of an array: [[0,"Description1"],[5,"Description2"]] could happen
A possible solution could be to split the string on a comma and use str[0] for the index and the other parts for the description but to me this would look like an ugly solution.
What should I do?
I use the following JS to save the rounds to a playerdata div from which i extract the list above (in which items is the list with the index and description)
function item_checkbox(items,n) {
return `
<input type="checkbox" style="display:none;" name="${itemList[n]}" value="${items}" checked>
`
}
function add_to_itemData(items, n) {
itemDataEl = document.getElementById(itemData[n])
itemDataEl.innerHTML = itemDataEl.innerHTML + item_checkbox(items, n)
}
Thanks for any help in advance
While you say that it would be an "ugly" solution to solve it by splitting, I think it's a pretty straightforward routine, given the format the data is returned to you.
['0,This is a testround', '1,This is a new testround'].map(v => v.split(','));
... would translate correctly to:
[
[ "0", "This is a testround" ],
[ "1", "This is a new testround" ]
]
But I guess I get what you mean. There are a few possible problems - for example, that of key uniqueness. You could solve this one by keeping each row into Javascript objects instead of arrays, and you can convert it quite easily by using Object.fromEntries(), since it conveniently accepts each row of bidimensional arrays as key/value pairs:
Object.fromEntries([
[ "0", "This is a testround" ],
[ "1", "This is a new testround" ],
[ "1", "This is a dupe testround" ] // this will overwrite the previous entry
]);
// {0: "This is a testround", 1: "This is a dupe testround"}
You might want to take a few extra steps for additional control, like using .trim() to remove leading or trailing whitespaces or testing/filtering/splitting them using a custom regex.

Working with 2D array in D3

I'd like to visualize data pulled in from the census data API, specifically from the ACS survey.
The data is returned in a non-standard version of JSON, as a two-dimensional array. It basically looks like this:
[
[
“POPULATION”,
“DATE”,
“ANOTHERTHING”
],
[
“ALABAMA”,
“2000”,
“MORESTUFF”
],
[
“ALASKA”,
“2000”,
“OTHERSTUFF”
],
…
]
I'm unfamiliar with working with this kind of JSON data, which almost looks more like a CSV, where the keys are written in the first line, and the values in every line after the first.
Is anyone familiar with how to parse and work with this data in D3, without having to go convert it first (i.e. https://gist.github.com/sarfarazansari/7e8ae05168b80b36016eb1c561a82f73)? (I'd like to draw from the data API directly).
Any help or guidance would be much appreciated.
First of all: do not use smart quotes (“) in a JSON (or in your code, whatever it is). I reckon that your real JSON is correct, this just happened because you used a text editor, like MS Word, to write this question. Also, there is no such a thing like non-standard JSON, because there is no standard JSON to begin with. You just have a JSON which is an array of arrays, nothing special here.
That being said, you can use that exact data structure to create your charts... However, specially if you're a beginner, it's a good idea to stick with the most common (here we can say standard) way to organise the data in D3 codes, which is an array of objects.
We can easily convert that array of arrays in an array of objects, which will be more comfortable to you.
First, supposing that your array is named data, let's extract the headers:
var keys = data.shift();
That not only creates a headers array, but it will remove the first inner array from the data array.
Now, we iterate over each inner array, creating an object with all the key/value pairs we need:
var newData = data.map(function(d) {
var obj = {};
d.forEach(function(e, i) {
obj[keys[i]] = e;
});
return obj;
});
There are shorter ways to do this, the one above is quite verbose but it is more didactic.
Here is a demo using the data you shared:
var data = [
[
"POPULATION",
"DATE",
"ANOTHERTHING"
],
[
"ALABAMA",
"2000",
"MORESTUFF"
],
[
"ALASKA",
"2000",
"OTHERSTUFF"
]
];
var keys = data.shift();
var newData = data.map(function(d) {
var obj = {};
d.forEach(function(e, i) {
obj[keys[i]] = e;
});
return obj;
});
console.log(newData)
<script src="https://d3js.org/d3.v5.min.js"></script>

Getting a value from the 2 dimensional array in Javascript

In this program I am supposed to create an 2 dimensional array such as ["S1","S2","S3","S4"] AND ["John","Ben","Dan","Jim"] and give the name as output when the specified serial no is given as input. Eg. John will be the output of S1.I was able to create the program using objects but I am unable to do it with arrays. I dont know how to create a 2 dimensional array as well. Kindly help.
Thanks.
Assuming you mean nested arrays and the result you are after is:
[ [ 'S1', 'S2', 'S3', 'S4' ], [ 'John', 'Ben', 'Dan', 'Jim' ] ]
Consider the following:
var mainArray = [];
var arr1 = ["S1","S2","S3","S4"];
var arr2 = ["John","Ben","Dan","Jim"];
mainArray.push(arr1, arr2);
This should give you the result you are after. Please keep in mind that your question is a bit vague and doesn't tell us what you have tried. It sounds like you need some practice with basic JavaScript. I suggest finding tutorials online(which there are more than enough) and working through them.
For future reference, be sure to show what you have tried in your question.

complicated custom sorting in nested array

I've problem sorting my nested array, says I've json like this
var orders = [{
'orderId': 1,
'sales': [{
'salesNumbers': 3
}]
}, {
'orderId': 2,
'sales': [{
'salesNumbers': 4
}]
}];
and I wish I can sort orderId base on salesNumbers. You may say it's impossible or I made a mistake by putting sales as array but it contain only 1 object which is salesNumbers. That's not a mistake, I just do not want to simplify my problem.
so it's possible to, without changing the data structure, sort orderId base on salesNumbers?? My app demo http://jsfiddle.net/sq2C3/
Since you say the sales array only has one item in it, you can order by salesNumbers like this:
orderBy:'sales[0].salesNumbers'
Here is an update of your fiddle: http://jsfiddle.net/wittwerj/sq2C3/2/

Categories

Resources