0

I've got arrays nested like this:

[["1", "apple 1"], ["1", "pear 2"], ["2", "lemon 1"], ["12", "lemon 12"]]

I'd like to replace all the occurrences of 1, 2, and 12 at nested array index 0 with "one", "two", and "twelve" respectively, so the result is this:

[["one", "apple 1"], ["one", "pear 2"], ["two", "lemon 1"], ["twelve", "lemon 12"]]

How do I do it?

0

3 Answers 3

1
var arr = [
    [ '1', 'apple 1' ], [ '2', 'pear 2' ], [ '3', 'lemon 3' ]
]

var numbers = [ 'one', 'two', 'three' ]

arr.forEach(function (el) {
    el[0] = numbers[el[0]]
})

arr // [ [ 'one', 'apple 1' ], [ 'two', 'pear 2' ], [ 'three', 'lemon 3' ] ]

Array indexes are actually strings, that's why numbers['2'] ('2' being a string) would retrieve the third member.

To iterate over the array, you could use a for-loop, but forEach looks nicer.

Sign up to request clarification or add additional context in comments.

4 Comments

Just be careful that forEach isn't supported in Internet Explorer prior to IE9.
Thanks, @Bill. Also, you can use es5-shim to support legacy browsers.
8kb of code because you like the look of a forEach loop more than a for loop? That seems pretty extreme...
@Bill, I don't only love forEach, map, filter, bind, Object.create and others, but also want these features to be perceived as ubiquitous and selbverstandlich. Progress is made through common effort.
0

something like :

var obj = [["1", "apple 1"], ["1", "pear 2"], ["2", "lemon 1"], ["12", "lemon 12"]];

for ( i = 0; i < obj.length ; i++ ) {
    switch(obj[i][0]) {
        case "1" : obj[i][0] = "one"; break;
        case "2" : obj[i][0] = "two"; break;
        case "12" : obj[i][0] = "twelve"; break;
    }
}

here is a jsFiddle : http://jsfiddle.net/dKZW5/1/

Comments

0

Edit

It seems I forgot to mention: this solution requires you to JSON encode the array: var workArr = JSON.stringify(theArr).replace(..). And once you're done: theArr = JSON.parse(workArr);

The quickest thing I could come up with is either do this:

var str = '[["1", "apple 1"], ["1", "pear 2"], ["2", "lemon 1"], ["12", "lemon 12"]]'.replace(/(\[")12/g,'$1twelve').replace(/(\[")2/g,'$1two').replace(/(\[")1/g,'$one');

But there are a couple of catches here: if write the replace(/(\[")12/g,'$1twelve') after you've replaced the ones, it won't work. so to get around this, you could do:

str = '[["1", "apple 1"], ["1", "pear 2"], ["2", "lemon 1"], ["12", "lemon 12"]]'.replace(/(\[")12"/g,'$1twelve"').replace(/(\[")2"/g,'$1two"').replace(/(\[")1"/g,'$one"');

Adding the closing quote. A more elegant solution, however is to create an object:

var replace = {'1':'one','2':'two','12':'twelve'};

And use the matched number as a property name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.