-4

This is what I'm trying to do, I have an array

var arr = [1, 2, 3, 4, 5];

then I want to create a new array each time by removing an item once i.e when i remove item at index 0 i should have [2, 3, 4, 5]and when i remove an item at index 1, I should have [1, 3, 4, 5] and so on till i get to arr.length-1 and each time i remove an item i still want my arr to be intact unchanged using javaScript I have tried some array methods like splice, slice but all that changes the value of arr how do i go about it with either javascript or python.

ozgur
  • 41,172
  • 16
  • 73
  • 106
Seun Adekunle
  • 123
  • 1
  • 9
  • 1
    Most obvious way is to make a copy of `arr` and then remove from that copy. – Alex Hall May 02 '17 at 20:50
  • Possible duplicate of [How to remove a particular element from an array in JavaScript?](http://stackoverflow.com/questions/5767325/how-to-remove-a-particular-element-from-an-array-in-javascript) – HaveSpacesuit May 02 '17 at 20:53
  • Possible duplicate of [How can you sort an array without mutating the original array?](http://stackoverflow.com/questions/9592740/how-can-you-sort-an-array-without-mutating-the-original-array) – keepAlive May 02 '17 at 21:01

3 Answers3

0

For JavaScript:

Try making a copy with slice() (slice returns a shallow copy of the array that you can manipulate without affecting the original array) and then using splice() to remove the value at your desired index:

newArray = slice(arr).splice(index, 1);
sadq3377
  • 667
  • 4
  • 13
0

For Python:

array = [1,2,3,4,5];

newarray = [value for counter, value in enumerate(array) if counter != 0 ]

PS each time you will use this list-comprehension, array will not be modified! so basically you will get the same output for newarray.

If you want to have newarray each time removed one element you need to create a function instead of list-comprehension (of course it's possible but will likely be less readable).

Community
  • 1
  • 1
anselmos88
  • 11
  • 1
0

For Javascript, using ES6 array spread operator and slice method,

var new_array = [...a.slice(0, index), ...a.slice(index + 1)];

const cut = (a, i) => [...a.slice(0, i), ...a.slice(i + 1)];

let arr = [2, 2, 2, 4, 2];
console.log(cut(arr, 3));
console.log(arr);
Coldiary
  • 196
  • 1
  • 4
  • 1
    I know, the spread operator is neat, but in this case I'd prefer the old way: `var new_array = a.slice(0, index).concat( a.slice(index + 1) );` because it does the same, just without the Array destructuring, and therefore slightly more performant. Just as an extension to your answer. – Thomas May 03 '17 at 10:13