Hello guys, how do I do arithmetics with a certain index from an array ? JavaScript

Joined
Dec 7, 2022
Messages
5
Reaction score
0
My assignment is to implement the getLocation function, that accepts 2 parameters:

  • coordinates — the array of initial coordinates in the [x, y] form;
  • commands — the array with command history in the ['command1', 'command2', 'command3' ...] form.

  • 'forward' means y + 1;
  • 'back' means y - 1;
  • 'right' means x + 1;
  • 'left' means x - 1.

For example, we have the coordinates = [2, 1] and commands = ['left', 'back', 'back'] arrays:
  • coordinates after the first command — [1, 1] (1 step left);
  • coordinates after the second command — [1, 0] (1 step back);
  • coordinates after the third command — [1, -1] (1 step back);
  • the result is the [1, -1] array.


My function:

function getLocation(coordinates, commands) {
let x = coordinates[0];
let y = coordinates[1];
let newArr = [];
for(let i = 0; i <= commands; i++){
if(commands === 'forward'){
newArr.push(y + 1);
}else if(commands === 'back'){
newArr.push(y - 1);
}else if(commands === 'right'){
newArr.push(x + 1);
}else if(commands === 'left'){
newArr.push(x - 1);
};
};
return newArr;
};

If i try to use the function with coordinates = 1, 2, commands = 'right' for example, it should return 2, 2,but it returns an empty array.
 
Joined
Jul 3, 2022
Messages
93
Reaction score
23
JavaScript:
function getLocation(coordinates, commands){
   let [x, y] = [...coordinates];
     for(let i of commands){
      i == 'back' ? y-- :
      i == 'left' ? x-- :
      i == 'forward' ? y++ :
      i == 'right' ? x++ :
      null;
     }
     return [x, y];
    }
   
    console.log( getLocation([2, 1], ['left', 'back', 'back']) ); // [1, -1]
    console.log( getLocation([1, 2], ['right']) ); // [2, 2]
 
Joined
Dec 7, 2022
Messages
5
Reaction score
0
JavaScript:
function getLocation(coordinates, commands){
   let [x, y] = [...coordinates];
     for(let i of commands){
      i == 'back' ? y-- :
      i == 'left' ? x-- :
      i == 'forward' ? y++ :
      i == 'right' ? x++ :
      null;
     }
     return [x, y];
    }
  
    console.log( getLocation([2, 1], ['left', 'back', 'back']) ); // [1, -1]
    console.log( getLocation([1, 2], ['right']) ); // [2, 2]
It works, thank you sir !
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,001
Latest member
Kendra00E1

Latest Threads

Top