what i want to get?
let arr2=['aa','bb','cc','dd'];
let arr3=arr2;
arr2.remove('bb');
console.log(arr2);//['aa','cc','dd'];
console.log(arr3);//['aa','cc','dd'];
arr3.remove('aa');//['cc','dd'];
console.log(arr2);//['cc','dd'];
console.log(arr3);//['cc','dd'];
here is my first thoughts about how to get: first: find index of item second switch position
let index=arr2.findIndex(item);
arr2[index]=arr2.at(-1);
arr2.pop();
//switch last one and ele of index
what i want to get?
let arr2=['aa','bb','cc','dd'];
let arr3=arr2;
arr2.remove('bb');
console.log(arr2);//['aa','cc','dd'];
console.log(arr3);//['aa','cc','dd'];
arr3.remove('aa');//['cc','dd'];
console.log(arr2);//['cc','dd'];
console.log(arr3);//['cc','dd'];
here is my first thoughts about how to get: first: find index of item second switch position
let index=arr2.findIndex(item);
arr2[index]=arr2.at(-1);
arr2.pop();
//switch last one and ele of index
You can remove elements from an array in-place with .splice
:
let arr2 = ['aa','bb','cc','dd'];
let arr3 = arr2;
remove(arr2, 'bb');
console.log(arr2);//['aa','cc','dd'];
console.log(arr3);//['aa','cc','dd'];
remove(arr3, 'aa');//['cc','dd'];
console.log(arr2);//['cc','dd'];
console.log(arr3);//['cc','dd'];
function remove(arr, item) {
let index = arr.indexOf(item);
if (index !== -1)
arr.splice(index, 1);
}
You can also add this remove
function to the array prototype, but I wouldn't do it. There are multiple good reasons to not do it. But if you really want the code in your question to produce the expected results, you can do this:
Array.prototype.remove = remove;
let arr2 = ['aa','bb','cc','dd'];
let arr3 = arr2;
arr2.remove('bb');
console.log(arr2);//['aa','cc','dd'];
console.log(arr3);//['aa','cc','dd'];
arr3.remove('aa');//['cc','dd'];
console.log(arr2);//['cc','dd'];
console.log(arr3);//['cc','dd'];
function remove(item) {
let index = this.indexOf(item);
if (index !== -1)
this.splice(index, 1);
}
But again, it's technically possible, but it's bad practice and you shouldn't do it.
remove
method, that removes elements in-place. You can use.splice
– jabaa Commented Feb 1 at 13:01