This question already has answers here:
Trying to sort a custom JavaScript object
(5 answers)
Closed 8 years ago.
I know, I've found many examples to sort an Object. But that makes me a little bit confused (I am not so pro to check wich is the fastest and cleanest method for me).
I hope somebody can help.
My Object looks like
tt_results = {};
tt_results[6815631] = new Array('85', 'blibee', 'blaerb', 'bluo', 'tkone', 'tkeeee_seve', '382261471' );
tt_results[1563157] = new Array('25', 'blib', 'blab', 'bluerro', 'tkerone', 'tk_seve', '382266851' );
I want to sort the timestamp.
Thanks in advance!
Peter
As has been mentioned in the comment you cannot sort objects.
In terms of general js performance a good resource for x-browser tests & results check out jsperf. There is an array sort test here
See my answer to a similar question here: Trying to sort a custom JavaScript object
Basically, you can't sort objects themselves - it doesn't make sense. But you can process the object in sorted order by sorting the keys and then iterating over the sorted keys.
Related
This question already has an answer here:
How to merge each object within arrays by index?
(1 answer)
Closed 4 months ago.
This is the data:
data=[{"id":1,"name":"vikash","roll":39},{"id":2,"name":"kumar","roll":3}]
data2=[{"hobby":"football","food":"any"},{"hobby":"basketball","food":"any"}]
list1=[]
expected Output:
list1:[{"name":"vikash","roll":39,"hobby":"football","food":"any"},{"name":"kumar","roll":3,"hobby":"basketball","food":"any"}]
Please help me!
Providing both lists are the same length, you're happy there are no key conflicts and you're using Python...
data=[{"id":1,"name":"vikash","roll":39},{"id":2,"name":"kumar","roll":3}]
data2=[{"hobby":"football","food":"any"},{"hobby":"basketball","food":"any"}]
list1 = []
for k, v in enumerate(data):
list1.append({**v, **data2[k]})
print(list1)
However in the future please be more concise when asking your questions.
Specify the language
Don't include redundant tags (eg - this question has nothing to do with Django)
Tell us what you've tried!
Also... the "please help me" line isn't required. The whole purpose of this community is to help each other so again this is redundant!
A simpler to understand solution
data=[{"id":1,"name":"vikash","roll":39},{"id":2,"name":"kumar","roll":3}]
data2=[{"hobby":"football","food":"any"},{"hobby":"basketball","food":"any"}]
list1=[]
for i in range(len(data)):
del data[i]['id']
d_main = {}
d_main.update(data[i])
d_main.update(data2[i])
list1.append(d_main)
print(list1)
This question already has answers here:
How to get value at a specific index of array In JavaScript?
(8 answers)
Closed 2 years ago.
so I am currently learning javascript on Codecademy. And a weird kind of thing got introduced that I don't quite get.
if you look at the code. you see at the end in console that after logging animals it is a [i] like why is that there? I get that is has something to do with the for loop. But I don't quite understand like why or what that it does. I don't know if question is clear enough but if you just try to explain why it is there and what it does there. that would be greatly appreciated:)
const animals = ['Grizzly Bear', 'Sloth', 'Sea Lion'];
for (let i = 0; i < animals.length; i++){
console.log(animals[i]);
}
the bracket notation is used to specify the index of the array you are looping through. You can always read more about javascript arrays on w3schools
This question already has an answer here:
If we create an array of objects using new Array(len).fil({}); and then add a key in any of the objects, it gets reflected in all the 3 objects
(1 answer)
Closed 4 years ago.
So my question is the same as in the title. I saw that someone initiated a similar thing here (If we create an array of objects using new Array(len).fil({}); and then add a key in any of the objects, it gets reflected in all the 3 objects) but while everyone accused the improper method of questioning nobody gave a clear answer.
Array(3).fill([]) creates 3 elements referencing the passed object.
The answer is clear in javascript documentation:
The fill() method fills all the elements of an array from a start
index to an end index with a static value
It seems to me like the only answer in the question you linked to is perfectly clear.
Array.fill "fills" the array with static values. That is to say, you are creating on single empty array and then referencing it in all three of the locations, hence it is the same array in each of the outer array's indices
This question already has answers here:
Sort array of objects by string property value
(57 answers)
Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?
(2 answers)
Closed 5 years ago.
I'm having trouble sorting a specific array of objects from a small personal project I'm working on. I have never had trouble using the Array.prototype.sort() function before, but I wonder if something about the multiple object keys is affecting it...
Been staring at it for longer than I care to admit and just need to ask for help now. :|
Goal: Sort array of objects alphabetically relative to a specific key.value on each of them.
Thanks in advance!
JS Fiddle Here
Sort function example - (I recommend looking at the full Fiddle for context though).
var sorted = array.sort((a, b) => { return a.key > b.key; });
SOLVED
#Ryan helped me find that returned a boolean isn't enough, you need to explicitly return a positive or negative number, or 0.
#Brk showed me an awesome quick way to do it.
This post has a very detailed description.
Sorting in JavaScript: Shouldn't returning a boolean be enough for a comparison function?
Thanks all! Sorry for the duplicate post :|
You can use localeCompare method which will returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
var sorted = array.sort((a, b) => {
return a.subreddit.localeCompare(b.subreddit)
});
DEMO
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 7 years ago.
I get an array of objects from the backend as this one, currently only three elements but in the future will be more.
[{"code":"lng.dropdown.home","text":"Inicio"},
{"code":"lng.dropdown.shop","text":"Tienda"},
{"code":"lng.button.support","text":"Soporte"}]
What is the most efficient way in javascript to find an element in this array by code, and return the text associated? Can we use lambdas expresions here?
you can use array filter to find the nested object(s) that matches your code property:
var arr =
[{"code":"lng.dropdown.home","text":"Inicio"},
{"code":"lng.dropdown.shop","text":"Tienda"},
{"code":"lng.button.support","text":"Soporte"}];
var res = arr.filter(function(x){
return x.code == 'lng.dropdown.home'
})
console.log(res[0])
[].filter returns an array with the objects that return true inside the callback.
As far as efficiency is concerned for loop are proved to be faster but using higher order methods you earn abstraction .
When not using other libraries, I usually map then find the indexOf, as follows:
data[data.map(function(a){ return a.code }).indexOf("code I am trying to find")];
This returns the element of data at the index where code matches the code you're trying to find.
When I have lodash as a dependency, I usually just do this however:
_.find(data, {code:"code I am trying to find"})
(I think that's the proper syntax)
Edit:
Didn't realize you were already using JQuery, the answer using $.grep is probably best.