Sort an array in Javascript/JQuery [duplicate] - javascript

This question already has answers here:
How to sort an array of objects with jquery or javascript [duplicate]
(6 answers)
Closed 8 years ago.
There is an array emails having few attributes To, From, Subject, Description. I retrieve records from database and populate all rows in this array. I use to access all rows as follows:
for (var i = 0; i < emails.length; i++) {
var To = emails[i].To;
var Sender = emails[i].Sender;
var Subject = emails[i].Subject;
var Description = emails[i].Description;
}
Now I need to sort this array alphabetically by To values and store the sorted emails in another array sortedemails. How can I do this in easiest possible way in Javascript/JQuery?
Thanks.

Arrays in javascript have a sort function.
emails.sort(function(a, b) {
if (a.To < b.To) {
return -1;
} else {
return 1;
}
}

JavaScript arrays have a built-in .sort method. No loops (or jQuery needed).
emails.sort(function(a, b){
return a.To.localeCompare(b.To);
});
This will modify the email array. If you want to save the original (unsorted) array, you'll need to copy the array before sorting.
var sortedemails = emails.slice(0);
sortedemails.sort(function(a, b){
return a.To.localeCompare(b.To);
});

Related

How to save a list with dicts in cookies in JS? [duplicate]

This question already has answers here:
Sort array by firstname (alphabetically) in JavaScript [duplicate]
(23 answers)
Closed 1 year ago.
I have a list of data which contains some dicts.
data = []
data[0]['id']=5 data[0]['title']=''
data[1]['id']=6 data[1]['title']=''
data[2]['id']=4 data[2]['title']=''
data[3]['id']=0 data[3]['title']=''
data[4]['id']=9 data[4]['title']=''
data[5]['id']=1 data[5]['title']=''
Yep, I fixed everything. Thank you.
What about cookies?
How can I save my list in JS cookies?
Sorting can be done like this:
data.sort((a, b) => a.id - b.id);
Array.prototype.sort is your friend here. Your Array will be mutated this helper method so you may want to copy it first.
let data = [], ids = [5,6,4,0,9,1]
for (let i = 0; i < ids.length; i++) {
data.push({id: ids[i], title: ''})
}
const sorted = data.slice(0).sort((a,b)=>a.id - b.id)

How to immutably insert into a sorted array? [duplicate]

This question already has answers here:
Efficient way to insert a number into a sorted array of numbers?
(18 answers)
Closed 3 years ago.
How do I immutably insert an element into a sorted array? (Let's assume an array of integers for simplicity)
The reason for this question: I'm writing a reducer for a React app, where the order of elements in my particular array is important.
The closest solution I've found is this one here, but it doesn't cover insertions into a sorted array.
Try this one.
let sortedArr = [1,2,5,9,12];
const newItem = 7;
for (let i = 0; i < sortedArr.length; i++) {
if (newItem <= sortedArr[i]) {
sortedArr = [...sortedArr.slice(0, i), newItem, ...sortedArr.slice(i)];
break;
}
}
console.log(sortedArr);

Javascript Object order incorrect [duplicate]

This question already has answers here:
How to keep an Javascript object/array ordered while also maintaining key lookups?
(2 answers)
Closed 7 years ago.
I have got a function which retrieves an object.
This object has a property and a value. The property is numeric and starts at "-30" all the way up to "50"
The problem is that when I loop through this object the browser seems to order it starting at "0" instead of starting at the initial property of "-30"
I need to make sure the order is exactly the same as the object.
var colorOj = {
"-30":"#111","-29":"#131313", ..etc.., "0":"#333", ..etc..,
"50":"#555"
}
function makeList(object){
for (var i in object) {
console.log(i); // Returns 0,1,2,3,4,5
// I need a return of -30,-29,-28,..., 0, 1, 2 ...
}
}
makeList(colorObj);
As suggested by #Teemu, properties are not stored in any specific order. But you can print them in any order using specific sort function accordingly.
Code
var obj = {};
for (var i = 5; i > -5; i--) {
obj[i * 10] = i * 10;
}
// Sort and get all keys...
var keys = Object.keys(obj).sort(function(a, b) {
return parseInt(a) - parseInt(b);
});
console.log(keys)
// Loop over keys to print values of each property
keys.forEach(function(item) {
console.log(item, obj[item]);
})
You can do something like this maybe:
var colorOj = {
"-30":"#111","-29":"#131313", "0":"#333",
"50":"#555"
};
var keys = Object.keys(colorOj).sort(function(a,b){return a - b})
for(var i = 0; i < keys.length;i++){console.log(keys[i])}
This way you can get every key in the object. Then sort it however you like(the sort function in javascript can take a compare function as a parameter look -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

Remove duplicates from array within array in Javascript [duplicate]

This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 7 years ago.
I started with an array formatted like this:
var cus = {
"acct":[
{
"latitude":"41.4903",
"longitude":"-90.56956",
"part_no":"P1140",
"no_sold":1
},
{
"latitude":"48.118625",
"longitude":"-96.1793",
"part_no":"227",
"no_sold":1
},
....
]
Next I put all of the part_no in a separate array like this:
var list = [];
$.each(cus.acct,function(index,value){
list = [value["part_no"]];
These are the results when I do a console.log() of my array:
["P1140"]
["227"]
["224"]
["600"]
.....
["756"]
["756"]
["756"]
How do I remove duplicates from this array of just part_no's with javascript/jquery? I've looked at other examples but can't find one that works for me. Take note that I'm just beginning with javascript as well.
function getUnique(arr){
var result = [];
$.each(arr, function(i, e) {
if(typeof e != "undefined")
{
if ($.inArray(e, result) == -1) result.push(e)
}
});
return result;
}
If you can use any libraries like underscope or lodash will provide more options.
I would use the jQuery unique option. It should remove any duplicates from your array.

pick random value from associated array using javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
JavaScript: Getting random value from an array
How can I choose an object key at random?
suppose we have an array like this:
var MrArray = new Array(5);
MrArray['one']='oneValue';
MrArray['two']='twoValue';
MrArray['three']='threeValue';
MrArray['four']='fourValue';
MrArray['five']='fiveValue';
ok?
the Array is associated.
and we have string key and string value.
now! how can i pick a random value from that?
Edit:i want to use like this:
Array Key Here
Regards
Sam
Using the method described here we can create the following function:
function randomKey(obj) {
var ret;
var c = 0;
for (var key in obj)
if (Math.random() < 1/++c)
ret = key;
return ret;
}
It returns a random key, so to get a random value from MrArray, do this:
var value = MrArray[randomKey(MrArray)];
jsPerf benchmark comparing the speed of this and the other answer.
Here:
function fetch_random(obj) {
var temp_key, keys = [];
for(temp_key in obj) {
if(obj.hasOwnProperty(temp_key)) {
keys.push(temp_key);
}
}
return obj[keys[Math.floor(Math.random() * keys.length)]];
}
Src: How can I choose an object key at random?

Categories

Resources