JS Slice only removes Items when they were in the Constructor - javascript

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.

Related

Javascript Delete item on sparse array and adjust length error

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.

How can I completely remove an object from an array in Javascript?

I have been using the following code:
formData.objectiveDetails.push(emptyObjectiveDetail);
This pushes a new emptyObjectiveDetail object onto the end of an array called objectiveDetails.
If for example the array of objectiveDetails contains 13 objects then how could I remove the one at position 5? I assume I could make this null but what I want to do is to completely remove it so the length of the array becomes 12.
This might be off topic but I have been considering adding underscore.js. Is this something that could be done with underscore?
formData.objectiveDetails.splice(5, 1)
First argument is the array index and the second the number of items to remove starting from that index.
You can use Splice to remove the object from the array. Something like this:-
formData.objectiveDetails.splice(5, 1)
Using underscore.js
objectiveDetails = _.without(objectiveDetails, _.findWhere(arr, {id: 5}));

How does this snippet for removing duplicates from an array work

Regarding this post (Remove Duplicates from JavaScript Array) on creating a new array of unique values from another array.
Code in question:
uniqueArray = myArray.filter(function(elem, pos) {
return myArray.indexOf(elem) == pos;
})
Using this as the test data:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
Desired result is an array with only unique values:
var unique_names = ["Mike","Matt","Nancy","Adam","Jenny","Carl"];
Where I'm at:
I understand that filter will run a function on each member of the array, and that elem is the element being reviewed, and that pos is its index. If something causes that function to return false, then that element will not be included in the new array. So walking through it, this happens:
Is myArray.indexOf("Mike") the same as 0? Yes, so add "Mike" to the new array.
Is myArray.indexOf("Matt") the same as 1? Yes, so add "Matt" to the new array.
Is myArray.indexOf("Nancy") the same as 2? Yes, so add "Nancy" to the new array.
[repeat for all elements. All pass.]
Basically I don't get why the 2nd Nancy would evaluate to false.
The indexof is the index of the first appearance of the element, so the second Nancy would get the index of the first Nancy, and would be filtered out.
6) Is myArray.indexOf("Nancy") the same as 5? No (it's 2, just like it step 3), so skip the duplicated "Nancy".
indexOf gives you the first occurrence of the item.

Javascript delete than splice

I am working on javascript project where I have 2 arrays 1. elements 2. elementsOrder ; elementsOrder array contains the names of each element, and elements array contains all properties of each element. When I want to delete one element from each array I do it with "delete" build in function, but it doesn't deletes element only sets it to Undefined, so than I use splice method to push out those undefined elements, but it doesn't work.
the is the source:
var s1 = elementsOrder.indexOf(id);
delete elements[s1];
delete elementsOrder[s1];
it does the job and sets elements one by one "undefined" smoothly, but when I do:
var s1 = elementsOrder.indexOf(id);
delete elements[s1];
delete elementsOrder[s1];
elements.splice(s1, 1);
elementsOrder.splice(s1, 1);
using simply splice methods don't work:
var s1 = elementsOrder.indexOf(id);
elements.splice(s1, 1);
elementsOrder.splice(s1, 1);
I use this piece of code in my Javascript Canvas project to animate some canvas objects, so I can easily see when "delete" works smoothly and "undefines" elements one by one, and splice doesn't works so smoothly and doesn't puts out elements one by one
Please see http://jsfiddle.net/7ZuuZ/ pay atantion to function animate, third function from bottom
Why not just splice in the first place?
var s1 = elementsOrder.indexOf(id);
elements.splice(s1,1);
elementsOrder.splice(s1,1);
There is no need to delete here.

Remove element from array, using slice

I am trying to remove a element from my array using slice, but i can't get it to work, look at this piece of code.
console.log(this.activeEffects); // Prints my array
console.log(this.activeEffects.slice(0,1)); // Remove from index 0, and remove one.
console.log(this.activeEffects); // Prints array again, this time my element should be gone
Result of this is.
So what is get from this is, at first the array is whole, as it should be. Then its prints what is sliced of the array. Finally the third should be empty? or?
function removeItemWithSlice(index) {
return [...items.slice(0, index), ...items.slice(index + 1)]
}
Slice will create a new array. We create two arrays: from beggining to index and from index+1 to end. Then we apply the spread operator (...) to take the items of those arrays and create a new single array containing all the items we care. I will paste an equivalent way if you don't like the one liner:
function removeItemWithSlice(index) {
const firstArr = items.slice(0, index);
const secondArr = items.slice(index + 1);
return [...firstArr , ...secondArr]
}
I believe you're looking for splice. From W3 Schools:
The splice() method adds/removes items to/from an array, and returns the removed item(s).
Take a look at the example on that page; the use case there is similar to what you want to achieve.
EDIT: Alternative link to MDN, as suggested by Nicosunshine; much more information about the command there.
a.slice(0, index).concat(a.slice(index + 1))
.slice does not mutate the array, you could use .splice() to remove the item at index i in the array:
this.activeEffects.splice(i, 1)
This is what I was able to come up with :
var newArray = oldArray.slice(indexOfElementToRemove+1).concat(oldArray.slice(0,indexOfElementToRemove));
Array.prototype.slice()...
does not alter the original array, but returns a new "one level
deep" copy that contains copies of the elements sliced from the
original array. Elements of the original array are copied into the new
array as follows:
Whereas Array.prototype.splice()...
Changes the content of an array, adding new elements while removing old elements.
This example should illustrate the difference.
// sample array
var list = ["a","b","c","d"];
// slice returns a new array
console.log("copied items: %o", list.slice(2));
// but leaves list itself unchanged
console.log("list: %o", list);
// splice modifies the array and returns a list of the removed items
console.log("removed items: %o", list.splice(2));
// list has changed
console.log("list: %o", list);
Look at here :
http://www.w3schools.com/jsref/jsref_slice_array.asp
You can see that the slice method select object et throw them into a new array object ^^ So you can't delete an object like this, may be you can try a thing like this :
var a = ["a","b","c"]; (pseudo code)
/* I wan't to remove the "b" object */
var result = a.slice(0,1)+a.slice(2,1); /* If you considers that "+" is a concatenation operator, i don't remember if it is true... */

Categories