How to Clone an Array With a Removed Element? [duplicate] - javascript

This question already has answers here:
How to get subarray from array?
(5 answers)
Closed 2 years ago.
I've searched up this question, and everywhere people seem to recommend to use array.splice(). However, splice is inplace, and, for example, in my javascript console editor.
Everywhere I seem to search, people say that splice does NOT mutate the original array, but that is clearly not the case. Now, I'm sure I will find another way to do what I want, but what is the proper way to make a copy of a piece of an array without affecting the original array?

You can use slice(), see below:
let x = [1, 2, 3, 4, 5]
console.log(x);
let sliced = x.slice(0, 2);
console.log(x);
console.log(sliced);
The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included) where begin and end represent the index of items in that array. The original array will not be modified.

Make a copy of the array using the spread operator and then you can use splice or whatever.
let arr = [1, 2, 3, 4, 5];
let newArr = [...arr];
console.log(newArr);
// newArr.splice(......)

Related

How is JavaScript splice affecting the array even before stating that I want to splice it? [duplicate]

This question already has answers here:
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Wrong value in console.log [duplicate]
(4 answers)
Closed 25 days ago.
Screenshot of the Output
This is a simplified version of the problem =>
const z = [
[1, 2, 3, 4, 5]
];
console.log(z);
z[0].splice(1, 1);
console.log(z);
Both Console logs output :
Array [ (5) […] ]
0: Array(4) [ 1, 3, 4, … ]
​length: 1
How is splice affecting the first console log?
​
I was making an algorithm then I noticed that even before calling the splicing function my original array which had thousands of items was getting affected meaning that the "History" or "Log" array that I was trying to form always had the same spliced version of the array that i later on tried splicing.
JavaScript's splice() method modifies the original array, meaning that it directly alters the array on which it is called. This is different from some other methods, such as slice(), which create and returns a new array without modifying the original.
const z = [
[1, 2, 3, 4, 5]
];
console.log(z);
//line below will affect the original array because array is
// refference in js
// z[0].splice(1, 1);
//instaed make a new deep copy of your variable z
const z2 = JSON.parse(JSON.stringify(z));
//now make the required changes to z2
z2[0].splice(1, 1);
console.log(z2);

comparing elements in an array in JS [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed last month.
How can I compare elements in an array like if I for example have arr=[1, 2, 3, 4, 4] and I wanna find out if there are any duplicates and remove them.Are there any fuctions that I can use for this?
you can use a set data structure inbuilt into JS
let arr=[1, 2, 3, 4, 4] ;
let output = [...new Set(arr)]
You need to convert the array to a set, A set has unique elements only as opposed to arrays that can have duplicates. To convert to a set
let arr=[1, 2, 3, 4, 4]
let set = new Set(arr);

Removing duplicates in array in javaScript using hasOwnProperty [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 5 months ago.
I have an array with duplicate elements. While trying to remove duplicate elements using hasOwnProperty getting one duplicate element in array rest of duplicate element removed successfully. expexted output = [1, 3, 2, 4, 5, 6, 7] but getting something [1, 3, 2, 3, 4, 5, 6, 7]. I can use different function and remove duplicates but I'm not understanding why element 3 is coming twice.
var array = [1,3,2,1,3,4,5,6,7,3,5,6,4,3]
let output = []
function removeDuplicates(array){
for(let item of array){
if(!output.hasOwnProperty(item))
output.push(item)
}
return output
}
console.log(removeDuplicates(array));
Instead of using hasOwnProperty, you can use includes.
var array = [1,3,2,1,3,4,5,6,7,3,5,6,4,3]
let output = []
function removeDuplicates(array){
for(let item of array){
if(!output.includes(item))
output.push(item)
}
return output
}
console.log(removeDuplicates(array));
hasOwnProperty checks whether an object contains a given key. The correct way to check if an array contains an element is to use includes:
if(!output.includes(item))
output.push(item)

Delete Javascript object item adding null value [duplicate]

This question already has answers here:
Deleting array elements in JavaScript - delete vs splice
(29 answers)
Closed 8 years ago.
I have an javscript object
finalTitleList =[{"Title":"ffd","Iscompleted":"","Id":0},
{"Title":"fdfmdbk","Iscompleted":"","Id":1},
{"Title":"fdf,d","Iscompleted":"","Id":2}]
Suppose i like to delete an 2nd item using delete finalTitleList[1], after deletion it delete the item but length is not updated(snapshot attached: contain only 2 item but showing length 3).
So when i am adding that object in localstorage using
localStorage.setItem("TaskTitleList16", JSON.stringify(finalTitleList));
On place of deleteditem it shows null.
I want to completely remove that item, please help me.
You're wanting Array.prototype.splice().
This is an example of usage:
var a = [1, 2, 3, 4, 5];
a.splice(2,1); // Being splice at element 2, deleting (and returning) 1 element
console.log(a); // outputs [1, 2, 4, 5]
Delete works a little differently than you may expect with arrays, and shouldn't really be used. For one, delete doesn't affect the length of the array. For two, it leaves this undefined value in the middle of the array, which means you'll have to deal with it in code using the array.
In summary, don't use delete on arrays. There's a ton of built-in methods that you can use to work with arrays, or compose together into your own operations. Use them.

How to remove elements from Array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to empty an array in JavaScript
How to remove all items from jQuery array?
I have array var myArray = [];, I want to clear all items in this array on every post back.
Simplest thing to do is just
myArray = [];
again.
edit — as pointed out in the comments, and in answers to other questions, another "simplest thing" is
myArray.length = 0;
and that has the advantage of retaining the same array object.
you can remove all item in myArray using array length, it's common pattern.
try this
var myArray = [1, 2, 3];
myArray.length = 0; // remove all item
To clear the array values you can do a simple:
myarray = [];
P.s.
jQuery != javascript
There is no such thing as a jQuery array, that's just a javascript array. When a page posts back, it re-renders and all of the javascript is re-run, you don't need to clear the contents of the array.
if, during execution of the page, you wanted to clear a javascript array, just re-initialize it as a new, blank array:
myArray = []; // no var, we are just initializing not declaring

Categories

Resources