Jquery array sorting not working as expected [duplicate] - javascript

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);

Related

Can someone explain how the routine below is logging "undefined" in console? [duplicate]

This question already has answers here:
Recursive function returns undefined
(3 answers)
Closed 2 years ago.
Code snippet below suppose to log sum of digits in the given number.But, it returns undefined. Can someone please explain how it works under the hood?
const checkNumbers = (membershipId) => {
if (membershipId.length === 1) {
return membershipId;
}
if (membershipId.length > 1) {
sumOfNumbers = [...membershipId].reduce((a, b) => +a + +b, 0);
checkNumbers(sumOfNumbers.toString());
}
};
console.log(checkNumbers("555"));
Because except for the length === 1 case, you don't have a return statement. If there's no return statement, then undefined is returned implicitly once the end of the function is reached.
To fix it, change this:
checkNumbers(sumOfNumbers.toString());
To this:
return checkNumbers(sumOfNumbers.toString());
Full code:
const checkNumbers = (membershipId) => {
if (membershipId.length === 1) {
return membershipId;
}
if (membershipId.length > 1) {
sumOfNumbers = [...membershipId].reduce((a, b) => +a + +b, 0);
return checkNumbers(sumOfNumbers.toString());
}
};
console.log(checkNumbers('555'));

if an array contains a specific value, then return the full 'content' of the value [duplicate]

This question already has answers here:
How to search for a string inside an array of strings
(8 answers)
Closed 7 years ago.
The idea is this..
var myArray = ['Apple juice','Banana Milkshake','Some Treat'];
function search(search_term){
if(myArray.indexOf(search_term) != -1){
return ..... //this is what i want to do.
};
// code is run as.
search("Apple");
My thought is when i call the search() function and it finds a value, it should return the full length or the full value of the matched term
so if i do search("Apple"); it should return 'Apple Juice'
but i don't know any way to do this so can anyone help me find a way to do this?
You can do the following:
for (var i in myArray)
if (myArray[i].indexOf(search_term) != -1)
return myArray[i];
Or if you want to return all matches in an array:
myArray.filter(function(item) {
return item.indexOf(search_term) != -1;
});
Maybe something like that ?
var myArray = ['Apple juice','Banana Milkshake','Some Treat', 'Here'];
function search(search_term){
for(var i=0; i < myArray.length; i++) {
if(myArray[i].indexOf(search_term) !== -1) {
return myArray[i];
}
}
return false;
};
// code is run as.
alert(search("Here"));

js array sort not working properly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm sorting an array of objects, but something in my evaluation is not working properly. Any insight would be really helpful, I'm starting to work in circles.
temp = [{name: 'M12-20'}, {name: 'M20-25'}];
a[field] = "M12-20"
b[field] = "M20-25"
temp.sort(function(a, b) {
var one = /[MFP]\d{2}/.exec(a[field]) || /[MFP]\d{1}/.exec(a[field]);
var two = /[MFP]\d{2}/.exec(b[field]) || /[MFP]\d{1}/.exec(b[field]);
return ( one[0] > two[0] ? 1 : -1);
});
I can only assume that what you're trying to do is extract the first number from each of those values and compare them, but if so, you're doing it incorrectly. a[0] and b[0] will produce the entire matched value if there is a match.
Your use of Regex is also more complicated than it needs to be.
Try this:
var temp = [{name: 'M12-20'}, {name: 'M20-25'}],
field = 'name',
r = /[MFP](\d\d?)/;
temp.sort(function(a, b) {
var one = r.exec(a[field]) || [,NaN],
two = r.exec(b[field]) || [,NaN];
return one[1] - two[1];
});
FYI (a side note) - Using return condition ? -1 : -1; in a sort comparison function is almost always wrong. The function needs to return 0 if the two values are equivalent in order. Neglecting to do this can result in incorrect results, inefficient behavior, or if you're really unlucky, an infinite loop.
Try this:
var temp=[];
temp[1]="Apple";
temp[2]="Orange";
temp[3]="Banana";
temp.sort(function(a, b) {
return return (a < b) ? 1 : -1;
});
From the source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;

Is there an easier way to sort a response object in JavaScript? [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 8 years ago.
At the moment I'm using the following to sort TypeCode (string) in a response object.
This seems a little over kill. Is there an easier way to achieve this with one for each loop?
if (response && response.length > 0) {
var sortedArray = [];
$.each(response, function (i, dict) {
sortedArray.push(dict.TypeCode);
});
sortedArray.sort();
$.each(sortedArray, function (i, dict) {
console.log(dict);
});
}
I assumed TypeCode was a number. You can pas a compareFunction to sort.
var sortedResponse = response.sort(function (d1, d2) {
return d1.TypeCode - d2.TypeCode;
});
If TypeCode is a string then:
var sortedResponse = response.sort(function (d1, d2) {
var type1 = d1.TypeCode, type2 = d2.TypeCode;
return type1 < type2? -1 : +(type1 > type2);
});
Sort the original response array, by providing a comparison function that compares the TypeCode properties of each element.
response.sort(function(a, b) {
return a.TypeCode - b.TypeCode
});
$.each(response, function(i, dict) {
console.log(dict.TypeCode);
});

Sort Array based on Object Attribute - Javascript [duplicate]

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".

Categories

Resources