js array sort not working properly [closed] - javascript

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;

Related

Does anybody know an alternative for php's `$a['mykey'][] = $a` in JavaScript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Basically I want to push value or create an array and add value to a dynamically created key through a loop. I can do this neatly in Php using [] operator.
foreach($array => $value){
$ret['mykey'][] = $value
}
This will create an array if not exist and push $value to it.
I am looking to do the same with JavaScript.
Edit
So far my approach is defining with a condition and then using array push.
if(!ret['mykey']){
ret['mykey] = []
}
ret['mykey'].push(value)
I am searching for replacement to this in one line statement.
PS: I believe objects are javascript's analogical replacement to PHP's associative array. Please correct me if I think wrong.
Something like this. You make changes accordingly.
x = ( typeof x != 'undefined' && x instanceof Array ) ? x : []
//or
var arr = arr || [];
Some thing along the lines of ...
Check if index exists as key in object, if not the add it as key and assign it blank array.
let a = {};
let index = 'mykey';
for (let i = 0; i <= 10; i++) {
if (typeof a[index] == 'undefined' || !(a[index] instanceof Array))
a[index] = [];
a[index].push(i + 10);
}
console.log(a);

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

Is there a way to check if an array holds more than one value? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
For example, what if I needed my code to have a certain set of numbers in an array list for something to happen? For example this array [1,3,4,5,9]. Is there any way I could check and see if an array contained all these integers at once and in the same order?
var arraySearch = function (subArray,array ) {
var i = -1;
return subArray.every(function (v) {
if(i != -1) {
i++;
return (array.indexOf(v) === i)
}
i = array.indexOf(v);
return i >= 0;
});
};
var arr = [1,3,4,5,9];
console.log(arraySearch([4,5],arr))
{1,3,4,5,9} is not an array. It's nothing valid in Javascript, for that matter.
myArray = [1,3,4,5,9] is an array. You can check the number of elements it contains with myArray.length.
Is there any way I could check and see if an array contained all these
integers at once and in the same order?
For this, you will have to provide some code of your own and show what you've tried first.
Fundamental
To check whether an array contain an element just once,
you may simply check if both indexOf and lastIndexOf yields exactly the same value and are greater then or equal zero.
var array = [1,2,3,3,3];
function isContainOnce(array,num){
return array.indexOf(num)>=0 && array.indexOf(num)==array.lastIndexOf(num)
}
// Try it
isContainOnce(array,3); // false
isContainOnce(array,10); // false
isContainOnce(array,1); // true
Now you can iteratively check the occurrence of such elements
function isContain(arr,sub){
var subArray = sub.slice();
var k = null;
while (subArray.length>0){
var s = subArray.shift(); // Take the first element to test
var i = arr.indexOf(s);
var j = arr.lastIndexOf(s);
if (i<0 || i!=j) return false; // Does not exist once
if (k && i-k!=1) return false; // Not in order
k = i;
}
return true;
}
To check whether [1,3,4,5,9,10,11,11] contains a sub array [1,3,4,5,9] with all elements in the same order:
isContain([1,3,4,5,9,10,11,11], [1,3,4,5,9]); // TRUE
Other cases
isContain([1,3,4,5,9,10,11,11], [5,9,10]); // TRUE
isContain([1,3,4,5,9,10,11,11], [2,3]); // FALSE
isContain([1,3,4,5,9,10,11,11], [10,11]); // FALSE because 11 occurs twice
If it's for an exact match:
yourArray.toString() === "1,3,4,5,9";
If the numbers you're searching for are a subset of the array, possibly with extra numbers in the middle, you have to loop through the elements.

how can you find the min number in this function in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
how can you find the min or max number in a function like this
{"a",5,"h",7,true,6,"h",7}. The solution must be applicable to other kinds of functions with the same characteristic.
I set min = arguments[0] but what if it's not a number?
you know i was reading about functions and I read about arguments objects,which contains an array of arguments.i tried this:
function argsMin() {
var i = 0;
var min=arguments[0];
for(i=0;i<arguments.length;i++) {
if(min>arguments[i]){
min=arguments[i];
}
}
return min;
}
document.write(argsMin(1124,562,-973,955));
now what if the first index is not a number.
Sweet and simple:`
var arr = ["a",5,"h",7,true,6,"h",7];
var min = Math.min.apply(null, arr.filter(function(el){
return typeof el == "number";
}));
//min = 5
And for older browser that do not support filter, use you can use polyfill (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Compatibility)
First for each element check if (typeof element== "number") and then check this to find min JavaScript: min & max Array values?
You can apply reduce function on the array to find min and max as followed.
min = array.reduce(function(x,y){if (typeof y === 'number' && (y<x)) return y; return x;}, Infinity)
max = array.reduce(function(x,y){if (typeof y === 'number' && (y>x)) return y; return x;}, -Infinity)
If there is no number in the array, min will contain Infinity and max will contain -Infinity
function minOfArray(array) {
return Math.min.apply(this, array.filter(function (a) { return !isNaN(a); }));
}
function maxOfArray(array) {
return Math.max.apply(this, array.filter(function (a) { return !isNaN(a); }));
}
Its actually really simple.
Just drop this inside of a loop:
Math.min(x, y);
Cycle through all of the elements and keep a variable lowest to hold the one that is lowest. Once all of the elements have been compared your lowest number will be held by the variable.
To determine if it is a number:
isFinite(String(foo).trim() || NaN)
Finally, look up "linear search" if going about this process confuses you.
Linear Search: http://en.wikipedia.org/wiki/Linear_search

getting opposite value javascript [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 have two strings: "a" and "b". How to get "b" from "a". And "a" from "b" without if? Like:
var arr = ["a", "b"];
function reverse(str){
return arr[+!arr.indexOf(str)];
}
but in more elegant way.
Many, many ways to do this.
var a = 'foo', b = 'bar',
arr = [a, b];
// dictionary object
var o = {};
o[a] = b;
o[b] = a;
function reverse(x) {
return o[x];
}
// equality with cast (+x or x|0)
function reverse(x) {
return arr[+(x === a)];
}
// or
function reverse(x) {
return arr[+(x === arr[0])];
}
If you just want to take turns between the two, you could write a generator
var reverse = (function () {
var i = 1;
return function () {
return arr[i = 1 - i];
}
}());
reverse(); // "foo"
reverse(); // "bar"
reverse(); // "foo"
You could do
return arr[(str=='a')%2]
or if you don't want to hardcode 'a'
return arr[(str==arr[0])%2]
or (using the same idea)
return arr[+(str==arr[0])]
It looks marginally cleaner than your solution but how is it better than using the ternary operator ?
Use the modulo operator.
var arr = ["a", "b"];
function reverse(str){
return arr[(arr.indexOf(str) + 1) % 2];
}
You can use char/ascii conversion:
function reverse(c) {
return String.fromCharCode(195 - c.charCodeAt(0))
}
Try it
alert(reverse('a'));
alert(reverse('b'));

Categories

Resources