Sort javascript object with array as value - javascript

I have a Javascript Object in the format key:pair where the pair is an array containing 2 timestamp values. I would like to sort this object so that the elements with the lowest numbers (earliest times) are displayed first.
Here is an example of the object: {"21_2":[1409158800,1409160000],"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600]}
So in this case, I would want the final sorted object to read:
{"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600],"21_2":[1409158800,1409160000]}
Obviously the sort() function will come into play here for the arrays, but how do I access those values inside the object? Note the object key isn't actually an integer because of the underscore.
I have found this: Sort Complex Array of Arrays by value within but haven't been able to apply it to my situation. Any help would be greatly appreciated.

You could change the structure of your data like this:
var myArray = [{
"id" : "21_2" // id or whatever these are
"timeStamps" : [1409158800,1409160000]
}, {
"id" : "20_1"
"timeStamps" : [1409148000,1409149200]
}];
Then you could sort it by the regular array sort:
myArray.sort(function(a, b){
// however you want to compare them:
return a.timeStamps[0] - b.timeStamps[0];
});

Related

Sort the array of database object-id

I have a array of mongodb object-id and i want to sort them in such a way that similar IDs are next to each other
example :
Input :
var array = ["507f191e810c19729de860ea","00000020f51bb4362eee2a4d",” 507f191e810c19729de860ea”]
Output :
var array = ["507f191e810c19729de860ea","507f191e810c19729de860ea","00000020f51bb4362eee2a4d"]
Simply sorting the input array would result in the same input array being sorted in natural order (converting the input to a string, if needed, and comparing the elements UTF-16 code units):
array.sort();
In case you would want the reverse order, you can reverse the array:
array.sort().reverse();

Can't figure out MYSQL query to get the result I want

I have a table called subcategories with columns 'id' and 'name' and a table called goals with columns 'id', 'name' and foreign key 'subcategory_id'.
I want a query that results in an array of subcategory objects, which has a property 'goals' which is an array of goal objects.
Too give an example of how the result would look In JS code:
result = [
{id: 1, name: "name", goals: [{id: 1, name: "goalName"}, {...}, {...}]},
{...},
{...}
]
But (with a different syntax) the result would be the same for other languages..
Thusfar I tried to do this with left-join, like this:
SELECT sc.ID as subcatId, sc.name as subcatName, g.ID as ID, g.name as name
FROM needs_subcategories as sc
LEFT JOIN needs_goals as g
ON sc.ID=g.subcategory_id
But the goals aren't grouped under a single subcategory.. I feel like it should be possible to do with a query, but I can't figure out/google how to do it because I wouldn't know how to phrase the question due to my lack of SQL knowledge..
Hope you guys can help me!
Thanks in advance.
You won't be able to acheive that with a query. MySQL can't do that.
You are currently fetching all goals, each one with their subcategory (subcategories will repeat).
You can convert it to the desired array with some code (example in php, you can translate this to any other language).
$result=array();
$lastSubcatId=null;
$goals=array();
while($row=$query->fetch_object()) { //assuming $query is the resultset
if($lastSubcatId&&$lastSubcatId!=$row->subcatId) {
$row->goals=$goals;
$result[]=$row; //or you could assign each desired property
$goals=array();
}
$goals[]=$row; //or you could assign each desired property
}
//surely, there are items left in $goals
if($lastSubcatId) {
$row->goals=$goals;
$result[]=$row; //or you could assign each desired property
}
But a more efficient way would be, I think, with multiple queries:
$result=array();
$subcats=$db->query("SELECT * FROM needs_subcategories");
while($subcat=$subcats->fetch_object()) {
//you might want to use prepared statements, I'm just simplifying
//it will not only be safer, but reusing the prepared statement will increase the performance considerably
$goals=$db->query("select * from needs_goals where subcategory_id=".$subcat->ID);
$temp=array();
while($goal=$goals->fetch_object()) $temp[]=$goal;
$subcat->goals=$temp;
$result[]=$subcat;
}
In the end I solved this using groupBy as #tadman suggested in his comment.
I created a function (based on the information in this answer) that looks like this:
function processResults(collection, groupKey) {
var result = _.chain(collection)
.groupBy(groupKey)
.toPairs()
.map(function (currentItem) {
// 'text' and 'children' are the keys I want in my resulting object
// children being the property that contains the array of goal objects
return _.zipObject(['text', 'children'], currentItem);
})
.value();
return result;
}
Which results in the array of objects with grouped goals! As I structured the function now (with hard-coded key names) it only works for my specific case, if you want to generalize the function you could add parameters amd replace the hard-coded key names with those.

Can anyone please tell how to iterate and use a json array of maps in jsp?

I have my json data (array of map) in my javascript and it's like as below:
[
{"HOURLY":"$309.75","Airport Fee":"$15.00","STC":"$52.66","Gratuity":"$61.95","Fuel Surcharge":"$5.00"},
{"HOURLY":"$309.75","Airport Fee":"$15.00","STC":"$52.66","Gratuity":"$61.95","Fuel Surcharge":"$5.00"}
]
I want to use the values of one of the maps in my jsp using some object.value or map.getValueBykey mechanism as if just like we use a model object passed from java to jsp.
Seeing that you have an array of objects, treat it first like an array. So,
prices = [
{"HOURLY":"$309.75","Airport Fee":"$15.00","STC":"$52.66","Gratuity":"$61.95","Fuel Surcharge":"$5.00"},
{"HOURLY":"$329.75","Airport Fee":"$15.00","STC":"$52.66","Gratuity":"$61.95","Fuel Surcharge":"$5.00"}
];
console.log(prices[0].HOURLY); // will output "$309.75", value found in the first object
console.log(prices[1].HOURLY); // will output "$329.75", value found in the second object
// If you want to get all values of that one property in all objects in the array, you can iterate like this:
for(var i =0;i <prices.length;i++){
console.log( prices[i].HOURLY);
}
// If you want to get all values for each property in a specific object, for example the first one in the array, you can iterate like this :
for(key in prices[0]){
console.log("'" +key + "' = " + prices[0][key]);
}
This is how it's done in JavaScript.
I see you are asking about JSP however. Maybe an example like this is what you are looking for:
javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>

How to initialize a hashmap of static values with integer keys in Javascript?

Initializing a map having string keys can be performed as following in Javascript:
var xxx = {
"aaa" : ["a1","a2","a3"],
"bbb" : ["b1","b2","b3"],
"ccc" : ["c1","c2","c3"],
...
};
I need to initialize some map with integer keys, something like:
var xxx = {
0 : ["a1","a2","a3"],
1 : ["b1","b2","b3"],
2 : ["c1","c2","c3"],
...
};
Of course, I could proceed with an array like this:
xxx[0]=["a1","a2","a3"];
xxx[1]=["b1","b2","b3"];
xxx[2]=["c1","c2","c3"];
...
but the issue is that it makes the initialization code long. I need to squeeze all the bytes I can from it, because I need to push this object on the user side and any saved byte counts.
The xxx object needs to be initialized with n arrays, and each entry has a unique associated id between 0 and n-1. So, there is a one to one mapping between the id I can use and the arrays, and these ids are consecutive from 0 to n-1, which makes me think I could use an array instead of a Javascript 'map'.
I have noticed that one can push objects into an array. May be I could use something like this:
var xxx = [];
xxx.push(["a1","a2","a3"],["b1","b2","b3"],["c1","c2","c3"],...);
Is this a proper to achieve my objective or is there something smarter in Javascript? Thanks.
P.S.: Later, xxx will be referenced with something like xxx[2], xxx[10], etc...
This strikes me as cleaner than using String or integer keys, though, unless you need to add additional properties on xxx:
var xxx = [
["a1","a2","a3"],
["b1","b2","b3"],
["c1","c2","c3"]
//...
];
Just make xxx into an array containing arrays. You can get at, say, "b3", via xxx[1][2] (because xxx[1] == ["b1", "b2", "b3"].)

is it valid javascript to access non-numeric key object with a numeric key?

I have an object
data = {
'choiceA' : 'Long-Wear',
'choiceB' : 'Anti-Age Lifting/Firming',
'choiceC' : 'Replenishing/ Moisturizing',
'choiceD' : 'Natural/ True-to-Skin',
'choiceE' : 'Smoothing/ Illuminating'
}
and I need to retrieve the fourth value given an integer
position = 3;
normally I would write
key = $.inArray( position, ['choiceA', 'choiceB', 'choiceC', 'choiceD', 'choiceE']);
answer = data[key];
but is it valid javascript to access the object directly with the numeric key like this?
answer = data[position]; // where position is an integer
EDIT:
some bad code I wrote as I'm using $.inArray backwards!
I meant to write
arr = ['choiceA', 'choiceB', 'choiceC', 'choiceD', 'choiceE'];
key = arr[position];
answer = data[key];
No, it is not valid until you have numeric object "keys", i.e.
data = {
'1' : 'Long-Wear',
'2' : 'Anti-Age Lifting/Firming',
'3' : 'Replenishing/ Moisturizing',
'4' : 'Natural/ True-to-Skin',
'5' : 'Smoothing/ Illuminating'
};
Also, it is important to note, that properties in JavaScript objects are not sorted. So your solution is the best way to go as I see.
if you would have tried it, you would have seen that it is not valid. even more it is not working!
data[position]
would return undefined in your example...
Two things:
Javascript keys are always strings. If you pass something else (say, a number) it is converted to a string. (For example, try indexing a array with array["3"] and it should work
Javascript objects are not ordered! You cannot get back the i-th key value pair portably. Instead you should use an array to store things (or something like that):
data = [
{ name:'choiceA', value: 'Long-Wear'},
{ name:'choiceB', value: 'Anti-Age Lifting/Firming'}
];
One thing you could do if you can't change the data representation is iterate though your object using a for-in loop, plus a counting variable. However, this approach is not portable, since not all browsers iterate in the same order as the keys were defined.

Categories