views:

53

answers:

3

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.

+1  A: 

Hello,

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

Alin Purcaru
+1 Good answer. gives the OP enough to go on without giving it to him on a plate.
Steve Claridge
+1  A: 
var emails = [], strings = [], numbers = [];

things.forEach(function (e) {
    if (typeof e == "string") {

        if (e.indexOf("@") != -1) { // "looks" like an email if it contains @
           if (isEmail(e)) emails.push(e); // push if it is a valid email
        }

        else strings.push(e);
    }

    else if (typeof e == "number") {
       numbers.push(e);
    }
 });

function isEmail(str) { return /** true if str is a valid email **/ }

I'll leave it up to you to come up with a correct isEmail function.

CD Sanchez
A: 
(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...

Šime Vidas
You assigned a, b, c to the same array. You need to assign each a new instance of an array otherwise you're pushing to the same array in memory.
CD Sanchez
Corrected. Thank you for pointing that out.
Šime Vidas