Home > Back-end >  Best way to replace middle element of array (dynamic) in Javascript
Best way to replace middle element of array (dynamic) in Javascript

Time:10-15

I am still pretty new to programing and have been working on challenges. One of them is creating a function that will:

-> Change the middle value in an odd array to a string "Hi" -> Return an even array as it is (no changes)

I have managed to find the middle element in the array with no problem (also setting up the condition for even arrays).

But I am struggling to figure out how to actually replace the element with a string and return the array.

For example [1, 2, 3, 4, 5] -> [1, 2, 'hi", 4, 5]

If anyone can point me in the right direction I would be very grateful. Thank you all for your help

function hiInTheMiddle(arry) {
  if(arry.length % 2 === 0) {
    return arry
  }
  let middle = arry[Math.floor((arry.length - 1) / 2)];
}

CodePudding user response:

You can simply change the middle element with arr[middle] = 'Hi'

So the code you need should be something like this:

let evenArr = [1, 2, 3, 4];
let oddArr = [1, 2, 3, 4, 5, 6, 7];

function hiInTheMiddle(arr) {
  if (arr.length % 2 === 0) {
    return arr;
  }
  
  arr[arr.length / 2 - 0.5] = 'Hi';
  return arr;
}

console.log(hiInTheMiddle(evenArr)); console.log(hiInTheMiddle(oddArr));

CodePudding user response:

You can simply achieve this requirement by just finding the index of middle element by using String.indexOf() method and then assign the hi string to that index.

Live Demo :

function hiInTheMiddle(arry) {
  if(arry.length % 2 === 0) {
    return arry;
  }
  let middle = arry[Math.floor((arry.length - 1) / 2)];
  arry[arry.indexOf(middle)] = 'hi';
  return arry;
}

const res = hiInTheMiddle([1, 2, 3, 4, 5]);

console.log(res);

  • Related