settingsAccountsettings
Menusettings

Q: Add / Remove elements

+6 votes

You will be given input lines containing 2 elements separated by a space. You can receive add command which’s second element is a number. You need to add that number to an array. You can also receive remove command and an index. You must remove the element at that index. If the index is nonexistent, ignore that input line. When you process all input data, print the array’s elements each on a new line.

Examples:

Input

Output

 

Input

Output

 

Input

Output

add 3

add 5

add 7

3

5

7

 

add 3

add 5

remove 1

add 2

3

7

add 3

add 5

remove 2

remove 0

add 7

5

7

 

asked in JavaScript category by user sam

1 Answer

+2 votes
 
Best answer

Here's the solution:

function addRemove(arr) {
  let numbers = [];
  for (var i = 0; i < arr.length; i++) {
    let pair = arr[i].split(' ');

    let command = pair[0];
    let number = Number(pair[1]);

    if (command == "add") {
      numbers.push(number);
    } else {
      numbers.splice(number, 1);
    }
  }
  for (let num of numbers) {
    console.log(num);
  }
}

// addRemove(['add 3',
//   'add 5',
//   'add 7']);

 

answered by user samfred5830
selected by user golearnweb
...