I have a sparse Array.
I use delete array[id] and I also want to adjust the length of the array after deletions. This is a pseudocode.
....
deleted =0;
...
if (condition) { delete array[id]; deleted++;}
...
array.length-=deleted;
Ok. I dont know what happen, the array has the expected length but ... it is empty!
Any idea what is happen?
Right way to delete an element from sparse array is :
arr.forEach(elm,index){
//delete index element
delete arr[index]
}
This removes the element but leaves the array size same
If you really want to do it manually and don't care about the order of items, the following is much faster than splice, but this messes up your order:
array[id] = array[array.length-1]; // copy last item to the index you want gone
array.pop(); // rremove the last item
The length of the array is automatically correct.
If you want to keep your order do what zerkms said and use splice
array.splice(id, 1);
The first parameter is the index from where you start. The second parameter is how many items you delete.
The length of the array is also correct.
Related
a = ['a','b','c','d','e'];
console.log(a.splice(1));
console.log(a);
In splice documentation, it says that skipping the delete parameter will delete all array items, yet here they're not; the first one is left out. Why is this?
Edit: My expectations was that haveing the omission of the delete parameter would cause to delete all the items of the array. But now after read Baconnier comment I understand that removes all after the index (first parameter).
then all the elements from start to the end of the array will be deleted. start being 1 in your case.
a = ['a','b','c','d','e'];
console.log(a.splice(0));
console.log(a);
Arrays start at 0, if you want to delete all elements including the first one you need to pass 0 as the first parameter.
I have color templates that users can choose between and also change the individual colors if they want. I have two arrays: one with all the templates, and each template containing a color palette of 8 total colors and a string of the template name. Most of my templates have white backgrounds, so I don't want the user to have to click 12 times or however many it takes to get to another index where the background color is different. My idea was to use a "for" statement to check the next element in my array, and compare it to the current element to see if they are identical. If the elements are identical, then I increment the array and the "for" statement checks again, effectively skipping any duplicate indices until a new value is found.
To do this, I use a "for" statement like this:
( ; array[index][colorSlot] == array[index+1][colorSlot]; index++)
This works perfectly until I get to the last array index and it looks for the next index which obviously doesn't exist, thus completely breaking my function. Is there a way to prevent it from looking into an array index that doesn't exist? Should I use something other than a "for" statement?
You'd prob want to go up to the second last array index and skip all repeats.
for(let index=0; index<array.length-2; index++)
{
if[index][colorSlot] != array[index+1][colorSlot]
{
}
}
You can try it with a while loop it's better choice than a for-loop in your case.
let index = 0;
while (index < array.length -2 && array[index][colorSlot] != array[index+1][colorSlot] ) {
...
index++;
}
Ok, I figured it out.
In my for loop, I check for two conditions: FIRST, I check to see if [index+1]!=array.length and THEN I check to see if the current array value is equal to the next (as written above). If checking the next value of the index would cause it to search an index that does not exist, it exits the for statement and resets my index.
Suppose I have an Javascript array,
var example = [and, there,sharma<br, />, ok, grt]
Now I want to randomly delete some array values - but not those values which have
<br
in them, in the above example, I want to make sure
"sharma<br" is not deleted.
I also do not want to delete "/>".
Can anyone help me. I would really appreciate the answer.
First of all, that is not a valid array, unless you are missing the string quotes. Anyway, what you are searching for is Array.Filter. In your case :
var filtered = example.filter(v => v.indexOf("<br") != -1 || v.indexOf("/>") != -1)
If I have understood the problem correctly, then you want to keep those entries in the array which have substrings "<br" and "/>"
If thats the case, you can try using javascript string method includes() to see if a string contains a particular substring.
JavaScript array must be created as below
var example = ["and"," there"",sharma<br","/>","ok"," grt"];
Using splice method , to delete the array values specifying the index positions.
array splice() method changes the content of an array, adding new elements while removing old elements.
Syntax
Its syntax is as follows −
array.splice(index, howMany, [element1][, ..., elementN]);
Parameter Details
index −
Index at which to start changing the array.
howMany −
An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
element1, ..., elementN −
The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.
Return Value
Returns the extracted array based on the passed parameters.
var removed = arr.splice(2, 2);
This would remove your suggested output to be my assumption .
This is the JSON stored in my chrome local storage
{"users":[
{"password":"123","userName":"alex"},
{"password":"234","userName":"dena"},
{"password":"343","userName":"jovit"}
]}
Is it possible to remove a specific item in "users" ?
I tried to this code but no luck
chrome.storage.local.remove('users[0]', function(){
alert('Item deleted!');
});
There is no magic syntax to delete only one element from an array that is stored in chrome.storage. In order to delete an item from the array, you has to retrieve the stored array, throw away the unwanted items (or equivalently, keep only the items that you want to keep), then save the array again:
chrome.storage.local.get({users: []}, function(items) {
// Remove one item at index 0
items.users.splice(0, 1);
chrome.storage.set(items, function() {
alert('Item deleted!');
});
});
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice.
Note that if you want to delete one or more items whose value satisfies a certain condition, you have to walk the array in reverse order. Otherwise you may end up removing the wrong items since the indices of the later elements are off by one after removing the first item, off by two when you've removed two items, etc.
Yes you can try this
chrome.storage.sync.remove("token");
see documentation
I try to remove the first Item so that all other move up in an Array I create with
..
Queue: [],
..
and dynamically push Items into.
I later use slice to remove them and have then next Item be the first one.
..
thread.Queue.slice(0, 1);
..
It should return the first Item of the Array, which it does, but it should also remove it from the array and move all other up.
Here is a example which shows, that is neither working in the Browser. (I found this 'behaviour' in Node.js)
http://jsfiddle.net/bTrsE/
or rather
http://gyazo.com/b3dcdbf4f74642c04fe1c1025f225a08.png
Array.Slice = Is an implementation of SubArray, From an array you want to extract certain elements from the index and return a new array.
Example:
var cars = ['Nissan','Honda','Toyota'];
var bestCars = cars.splice(0,1);
console.log(bestCars);
//This should output Nissan Because i like Nissan
For your problem you should be looking Array.Splice(), splice adds / removes an element from the index
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
The .slice() method does not alter the original array. It returns a shallow copy of the portion of the array you asked for.