-1

I'm pretty stuck, It should evaluate to ["present", "pretty", "precede"]

function addTooStart(x, y) {
  let a = [];
  let b = "";
  for (let i in x) {
    a = x.push(y);
    a = x[b]
  }
  return a
}

let abc = addTooStart(["sent", "tty", "cede"], "pre");
console.log(abc)
Phil
  • 157,677
  • 23
  • 242
  • 245
MikeHawk5
  • 3
  • 2
  • 1) Use more meaningful variable names. 2) [Don't use `for..in` on arrays](https://stackoverflow.com/q/500504/283366). 3) Assigning a new value to a variable discards the old value – Phil Mar 14 '22 at 00:00
  • `for (let word of x) a.push(y + word); return a` – Phil Mar 14 '22 at 00:01

1 Answers1

1

I'm not sure what your a and b are attempting to do here. Some problems from your code:

  1. x.push(y) adds the element y to the end of the array x, and then returns the new length of the array, so now a is a number.
  2. x[b] will always be an invalid call, since b equals the empty string and is never changed, arrays are integer indexed.

The general approach here would be to loop through the array x, like you did, then for each element, set it equal to "y + current element". I have attached a working version below.

function addToStart(x,y){
  for (let i = 0; i < x.length; i++) {
    x[i] = y + x[i]
  }
  return x
}

addToStart([ "sent", "tty", "cede" ], "pre"); // -> [ 'present', 'pretty', 'precede' ]
Pace
  • 26
  • 1