Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Simple javascript question:

I have an array (50=50; 49=49; 143=143; 4005=4005; ... )
which i want to turn into (50; 49; 143; 4005; ...).

The name will always be the same as the value, in the name=value pair.
It will always be a number (but of various lengths).

I just cant get my head around it using .split

Thanks

share|improve this question
2  
Could you please be more precise? Arrays of the form (50=50; 49=49; 143=143; 4005=4005; ... ) don't exist in JavaScript. We cannot help you if we don't know what you actually have. –  Felix Kling May 9 '12 at 12:34
1  
Do you mean to say you have a string of those values from which you want to make an array? –  Michael Berkowski May 9 '12 at 12:35
    
no point in defining useless array having all keys same as value –  Nitin Sawant May 9 '12 at 12:40
    
sorry. its from a js cookie –  Lan May 9 '12 at 12:43
    
You should clarify that in your question and provide a syntactically valid example. Otherwise it is not of much use to other people. –  Felix Kling May 9 '12 at 13:03

1 Answer 1

up vote 1 down vote accepted

Assuming that you mean you have an array like this:

var arr = ['50=50;','49=49;','143=143;','4005=4005;'];

Then, you may employ split like this:

var newArr = [], ii;
for (ii = 0; ii < arr.length; ii += 1) {
    newArr.push(parseInt(arr[ii].split('=')[0], 10));
}

This will result in newArr being equal to this:

var newArr = [50, 49, 143, 4005];

The way split works is it divides a string up into an array based on a delimiter string. In this example, we've used '=' as the delimiter, so we end up with arrays like this:

['50', '50;']
['49', '49;']
// etc.

Then, index into the first element and pass it to parseInt to produce a number, and push onto a new array with just number elements.

Here's a working example.

Addendum

If you aren't starting with an actual JavaScript array, but a string that you'd like to turn into an array, then add this step before the previous ones to get yourself the original array:

var str = '(50=50; 49=49; 143=143; 4005=4005;)';
var arr = str.replace(/\(|\)|;/g, '').split(' ');
share|improve this answer
    
great. exactly what i needed. just one question, what is the value 10 doing in your solution? thanks –  Lan May 9 '12 at 12:46
1  
When using parseInt, one should always specify the second parameter, which is the radix/base of the number you're parsing. That's why there's a 10. developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… –  FishBasketGordo May 9 '12 at 12:54
    
ahh. thanks a lot –  Lan May 9 '12 at 12:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.