Pinguluk
Pinguluk

Reputation: 46

Find in first array values and then change them with values from another array

First array

var danu = ["nu", "da", "nu", "da", "da", "da", "da", "da", "da", "nu", "nu"];

Second array

var abc2 = ["2", "3", "2", "3", "3", "2", "2"];

I want to replace all "da" from first array with the values from the second array 1 by 1 so i will get

["nu", "2", "nu", "3", "2", "3", "3", "2", "2", "nu", "nu"];

I want the fix only in Javascript. I tried using the loop metod

for (i=0; i<danu.length; i++) {
if (danu[i] == "da") {
 danu[i] = abc2[i];
}
}

But i end up getting the array to this

["nu", "3", "nu", "3", "3", "2", "2", undefined, undefined, "nu", "nu"]

Upvotes: 0

Views: 42

Answers (3)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You can use .map to apply changes on each item in the danu array. Then have a c count which increments when "da" was found.

danu = ["nu", "da", "nu", "da", "da", "da", "da", "da", "da", "nu", "nu"];
abc2 = ["2", "3", "2", "3", "3", "2", "2"];

c = 0;

newArr = danu.map(function(e,i){
    if(e == 'da') return abc2[c++];
    return e;
});

console.log(newArr);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386881

Just use Array.prototype.reduce():

var danu = ["nu", "da", "nu", "da", "da", "da", "da", "da", "da", "nu", "nu"],
    abc2 = ["2", "3", "2", "3", "3", "2", "2"];
  
danu.reduce(function (r, a, i, o) {
    o[i] = a === 'da' ? abc2[r++] : a;
    return r;
}, 0);

document.write('<pre>' + JSON.stringify(danu, 0, 4) + '</pre>');

Upvotes: 1

Branden Keck
Branden Keck

Reputation: 572

Assuming that the second array is equal in length to the number of "da" in the first array, the code would look like:

var j = 0;
for(int i; i<danu.length; i++){
    if(danu[i] === "da"){
        danu[i] = abc2[j];
        j = j + 1;
    }
}

However, if the second array is of different length, incrementing j could put abc2 out of bounds. You would need a different strategy based on what you are actually trying to accomplish with this.

Upvotes: 0

Related Questions