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.
Related
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.)
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'],
...
}
I came across the following nested array and am little confused as to why it uses this particular syntax:
var allQuestions = [{
question: "Which company first implemented the JavaScript language?",
choices: ["Microsoft Corp.", " Sun Microsystems Corp.", "Netscape Communications Corp."],
correctAnswer: 2
}];
Full example: http://jsfiddle.net/alxers/v9t4t/
Is it common practice to use
[{...}]
having declared a such a variable?
The definition is an array with an object literal in it. It is not realy a nested array. The
{
question: "Which company first implemented the JavaScript language?",
choices: ["Microsoft Corp.", " Sun Microsystems Corp.", "Netscape Communications Corp."],
correctAnswer: 2
}
is an object literal, which your array contains. In the fiddle you linked to there are several of these defined in the allQuestions array. By doing this it makes it easy to loop over the array of questions and display each in turn.
What's happening there is listing the object inside an array, example:
[{id:1, value:"any"}, {id:2, value:"any any"}]
So here we have declared array with two objects in it. Another so called "traditional" approach would be:
var arr = [];
var obj1 = {id:1, value:"any"};
arr.push(obj1);
...
The allQuestions variable is supposed to be "an array of questions", where each question is an object with properties like question, choices or correctAnswer.
If it was declared just as var allQuestions = {question: ..., choice: ...}, it would be just the one object. Further code which want to know the number of questions allQuestions.length or access e.g. the first question's test as allQuestions[0].question would not work.
Try adding more questions and you will see what the extra brackets are for:
var allQuestions = [
{ question: "1st...", ...},
{ question: "2nd...", ...},
...
];
allQuestions is just an array of objects and yes, it is common practise.
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/
I've got results being returned to a Google Mapping application in the div sidebar. The results are names of businesses that belong to categories that the client wants returned in a certain order. And unfortunately it's not a straight alpha sort. So one category begins with F and the second one with a C and the last three are A's, for example.
So I need my switch, which works, but naturally insists on dropping the values in alpha sorted (as they are returned from the DB that way) order as that's how it encounters them. What's the best way to set this up so I can grab my preferred categories with their associated company names in the arbitrary order the client has asked for?
Thanks!
Can you iterate over the categories in the order you want them in, and find the object to which it is associated?
E.g. (pseudocode)
var categories = [ 'F', 'C', 'A1', 'A2', 'A3' ].map(function (category) {
return businesses.filter(function (business) {
return business.category === category;
});
});
So the missing step in the answer given here was HOW the map would be implemented and HOW the JS snippet could be implemented. Anyway, I ended up having to ask that as a separate question and finally got a nice working example for an answer.
Russ wrote:
The code given looks most likely to be
using the jQuery JavaScript library
that has some useful functions such as
map() for manipulating arrays.
If we go back to the original problem,
you need to order a list of categories
based on the client's preference.
Let's create a an object literal to
map the ordering
var map = {
F : 5,
C : 3,
A1 : 1,
A2 : 4,
A3 : 2
}
We can use this map to order the array
using the sort method
var array = ['F', 'C', 'A1', 'A2', 'A3'];
array.sort(function(a,b) {
return map[a] - map[b];
});
This returns us ["A1", "A3", "C", "A2", "F"]
Anyway, I wanted to make sure this was included on this thread for anyone searching for this issue in the future or anyone following along right now. Thanks for everyone's input!