'javascript array sorting?
Given the following array:
var things = ['sandwich', 17, '[email protected]', 3, 'horse', 'octothorpe', '[email protected]', '[email protected]'];
Sort the array into three others, one of numbers, one of strings, and one of valid email addresses. Discard the invalid address.
Solution 1:[1]
What you need is to use the filter function of the Array object.
Example:
function isBigEnough(element, index, array) {
return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
You need to write 3 custom filtering functions for each of your needed arrays.
The first two conditions are trivial, as for the third one I recommend choosing a regexp that satisfies your exigence in validating emails. A short one would be ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$.
Regards, Alin
Solution 2:[2]
(function(arr) {
var a = [], b = [], c = [];
for (var i = 0; i < arr.length; i += 1) {
if (typeof arr[i] === "number") {
a.push(arr[i]);
} else if (isValidEmail(arr[i])) {
b.push(arr[i]);
} else if (typeof arr[i] === "string") {
c.push(arr[i]);
}
}
return [a, b, c];
}());
isValidEmail(s) returns true if the the argument is a string representing a valid e-mail. You are best of using a RegEx for this...
BTW, the way you use this is, you assign the above expression to a variable, and then this variable holds the three arrays as its items...
Solution 3:[3]
Here is one solution
function isBigEnough(el, i, array) {
return (el >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
Try this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alin Purcaru |
| Solution 2 | Å ime Vidas |
| Solution 3 | Kaium |
