Sort Array based on Object Attribute - Javascript [duplicate] - javascript

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 9 years ago.
I have an array of objects called canvasObjects.
Each object has an attribute called z.
I want to sort this array based on objects z. How do I do this using the sort() method?

You just need to pass in a comparator to the sort function
function compare(a,b) {
if (a.attr < b.attr)
return -1;
if (a.attr > b.attr)
return 1;
return 0;
}
canvasObjects.sort(compare);
Or inline
canvasObjects.sort(function(a,b) {return (a.attr > b.attr) ? 1 : ((b.attr > a.attr) ? -1 : 0);} );
See this POST

Tried other answers posted here but then I found the following to work best.
Ascending :
canvasObjects.sort(function(a,b) { return parseFloat(a.z) - parseFloat(b.z) } );
Descending :
canvasObjects.sort(function(a,b) { return parseFloat(b.z) - parseFloat(a.z) } );

Send anonymous function to the sort method which returns a subtraction of the property "z"
var arr = [{z:2},{z:4},{z:5},{z:1},{z:3}];
arr.sort(function(a,b) {return a.z - b.z});
above puts numbers in z to order 1,2,3,4,5. To reverse the order make it return "b.z - a.z".

Related

Javascript: How to compare a string against an array of strings [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 2 years ago.
I want to be able to check if a string is equal to any of the strings inside an array. I know you can check multiple parameters like so:
let value = 'sales';
if ( value == 'sales' || value == 'broker' ){}
But I need to use an array like:
let value = 'sales';
let array = ['sales', 'broker'];
if ( value == array ){}
How can I do this?
Use array.includes:
if (array.includes(value)) {
...
}
You use array includes which returns a Boolean
let array = ['sales', 'broker'];
function test( value ) {
if ( array.includes(value) ){
console.log('true', value)
} else {
console.log('false', value)
}
}
test('sales')
test('world')
You can also use filter function, which might be better especially if you later need some additional checks.
if(array.filter(el => el === value).length > 0){
//
}
You can use includes method to check if array contains a value.
let array = ['sales', 'broker'];
console.log(array .includes('sales'));
use includes method
if (array.includes(value)) {
}

Sorting Object Arrays With JavaScript [duplicate]

This question already has answers here:
Why is one string greater than the other when comparing strings in JavaScript?
(5 answers)
How does sort function work in JavaScript, along with compare function
(7 answers)
Closed 4 years ago.
I have an array:
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}]
and I want to sort cars object on type using this code
function myFunction() {
cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
displayCars(); // a function to output the result
}
x and y in this function is either saab, bww or volvo. How is it possible to compare (saab < bmw). I mean they are not numbers to be compared and return another number.
How does if conditional statements compares two strings rather than comparing numbers? and why does it has to return -1, 1 and zero?
Are you asking why this works?
If so, it works because JavaScript has some awareness of lexicographical order. B comes before S and S comes before V and so on.
-1 means that variable a should be moved one index lower than variable b.
1 means that variable a should be moved one index higher than variable b.
0 means that variable a should not be moved.

Jquery array sorting not working as expected [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 5 years ago.
Here is my array and i am trying to sort it. But it is not working as expected. i want to sort the name as descending.. How can i do it ?
var d = '{"success":"1","message":[{"_id":"591b39df358f1d1f843231d1","area":"chennai","food":"idly","name":"saravana bavan","__v":0},{"_id":"591b39e0358f1d1f843231d2","area":"Dindigul","food":"Dosa","name":"Kattu Briyani","__v":0},{"_id":"591b39df358f1d1f843231d4","area":"Tirupur","food":"Poori","name":"French Loaf","__v":0}]}';
console.log(d);
var results = jQuery.parseJSON(d);
console.log(results.message);
results.message.sort(function(a, b) {
return b.name- a.name;
});
console.log(results.message);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is my Fiddle
You can't perform mathematical operations on strings.
results.message.sort(function(a, b) {
if (b.name > a.name) { return 1 }
else if (b.name < a.name) { return -1 }
else { return 0 }
});
As #bergi mentioned in a comment below. This explains the problem in depth.
just change your comparison function as follows:
var d = '{"success":"1","message":[{"_id":"591b39df358f1d1f843231d1","area":"chennai","food":"idly","name":"saravana bavan","__v":0},{"_id":"591b39e0358f1d1f843231d2","area":"Dindigul","food":"Dosa","name":"Kattu Briyani","__v":0},{"_id":"591b39df358f1d1f843231d4","area":"Tirupur","food":"Poori","name":"French Loaf","__v":0}]}';
console.log(d);
var results = jQuery.parseJSON(d);
console.log(results.message);
results.message.sort(function(a, b) {
return b.name.toLowerCase() > a.name.toLowerCase() ? 1 : -1;
});
console.log(results.message);

Sort a javascript array of objects by object property

I am trying to sort an array. For instance, given array a (below), I would like to return array b.
I know I can do a.sort(), however, I don't want to sort on the actual array element, but on a property (s for this example) of the array element. How can this be accomplished?
Thank you
var a=[
{s:"ced",o:{obj:1}},
{s:"cde",o:{obj:2}},
{s:"ade",o:{obj:3}},
{s:"bde",o:{obj:4}}
]
var b=[
{s:"ade",o:{obj:3}},
{s:"bde",o:{obj:4}},
{s:"cde",o:{obj:2}},
{s:"ced",o:{obj:1}}
]
Array.prototype.sort accepts an optional parameter: a callback telling it how to sort.
a.sort(function(x,y) {
// do something here
// return -1 if x < y
// return 1 if x > y
// otherwise, return 0
});
So, in your case, it would be:
a.sort(function(x,y) {return x.s == y.s ? 0 : (x.s < y.s ? -1 : 1);});
a.sort(function(a, b){
if(a.s < b.s){
return -1;
}
if(a.s > b.s){
return 1;
}
return 0;
});
http://jsfiddle.net/lbstr/nCKpG/
The sort method accepts a compareFunction parameter, where you can define how to calculate sort order.
As you want to compare strings this function should use localeCompare as suggested here.
One way to create a sorting function which can be quickly adjusted is to generate it via another function. This means you can create sort functions automatically for any property of an object.
Put the two to together and you get..
function genSortFn(prop){
return function(a,b){ return a[prop].localeCompare( b[prop] ); };
}
a.sort( genSortFn('s') );
b.sort( genSortFn('s') );

Simple sort algorithm for names - Javascript

If I have an array of objects Array 1:[Object 1, Object 2, Object 3] and each object looks like the following:
object 1 has properties : creation date, name, class, size where name = Bear
object 2 has properties : creation date, name, class, size where name = Dog
object 3 has properties : creation date, name, class, size where name = Guerilla
And I want to sort these objects based upon their respective names in alphabetical order, so Array 2 looks like the following [Object 1 (Bear), Object 2 (Dog), Object 3 (Guerilla)]
how would I approach this problem in Javascript? Are there any convenience methods for doing this? I am relatively new to JS. Thank you in advance!
Use the sort method with a custom comparer:
Array1.sort(function(x, y){
var n1 = x.name;
var n2 = y.name;
return n1 == n2 ? 0
: n1 < n2 ? -1
: 1;
});
arr.sort(function (a, b) {
return a.localeCompare(b);
});
Note that sort is an in-place sort, so your original array will be sorted.
The javascript sort method accepts an anonymous comparison function that gives you all the flexibility that you would need to sort objects on any attribute.
The general pattern is:
arr.sort(function(a,b){...});
The "anonymous" function provided to the sort method accepts two objects to compare, and should return a value that indicates which element to sort higher, as follows:
if a should be sorted higher than b, return 1
if a should be sorted lower than b, return -1
if a is equivalent to b (for sorting purposes), return 0
Here's an example (ellipses indicate other attributes):
var beasties = [
{name:'Bear', created_at: ... },
{name:'Dog', ... },
{name:'Gorilla', ... }
];
beasties.sort(function(a,b){return a.name > b.name});
Here, I'm relying on the ability for js to compare the strings that are returned by the name attribute.
I think that ought to do the trick for you.
You can pass a custom compare function to Array.sort which will then be used by the sorting algorithm to decide which one of two array elements is larger. When the algorithm compares two objects, it passes these to the compare function. When the function returns 1, it considers the first one as larger. When it returns -1, it considers the second one larger. When it returns 0, it considers them equal.
function compare_function(obj1, obj2){
if (obj1.name == obj2.name) return 0;
if (obj1.name < obj2.name) return -1 else return 1;
}
my_array.sort(compare_function)
You can use the sort method of the array, and pass in a function:
Array1.sort(function(left,right) {
if (left.name < right.name) return -1;
if (left.name > right.name) return 1;
return 0;
});

Categories

Resources