0

I have one array which contains values array1 = [a,b,c,d,e,f,g] and another array contains index of array1 and the value to be replaced array2 = [[2,u],[3,x],[6,z]].

Now I want to replace value of array1 with respect to array2 please not array2 consist of [array1_position, value_to_be_replaced]

Now my new arra1 should look like this array1 = [a,b,u,x,e,f,z].

I can do this with for loop but its again time consuming. what trick can i use to replace the value quickly. I am just learning about arrays and have a little knowledge on it.

2
  • You can't do this without using a for loop. Commented May 30, 2020 at 9:44
  • just as @Ramesh said, you will have to do a loop regardless of the syntax and even the language itself. That being said the best runtime complexity u can get is O(array2.length), and that is my looping through array2 items and making the needed changes from there Commented May 30, 2020 at 9:49

4 Answers 4

1

I don't think there is any shorthand for such a verbose question. Something on top of my mind is

array2.forEach((el) => {
  array1[el[0]] = el[1];
})
Sign up to request clarification or add additional context in comments.

Comments

1

you could do this

array2.forEach(arr => {
   const [index, replaced] = arr;
   array1[index] = replaced;
});

Comments

1

You can take fromEntries of the other array then just map it:

var array1 = ['a','b','c','d','e','f','g'];
var array2 = [[2,'u'],[3,'x'],[6,'z']];
var d=Object.fromEntries(array2);
var result = array1.map((val, i)=> d[i] || val);
console.log(result);

2 Comments

what if my array2 = [2,'u','xyz'],[3,'x'],[6,'z'] and I need to do the same thing.
@Mask, It won't work then beacuse fromEntries works on key value pair, so in your case it will discard the xyz and take u and then create object.
1

With an ordered array2 by indices, you could take a closure over an index of this array and map the values from eithe the first array or the replacements array.

var array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
    array2 = [[2, 'u'], [3, 'x'], [6, 'z']],
    result = array1.map(
        (j => (v, i) => i === array2[j][0] ? array2[j++][1] : v)
        (0)
    );

console.log(result);

1 Comment

if array1 is extremely larger than array2 then performance will suffer, its better to loop through array2 and modify array1 in place for best runtime/memory performance.

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.