Remove element from array, using slice - javascript

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... */

Related

JS: Iterate over an array of objects to update object

I am trying to iterate over an array of array objects to de-dupe and sort the data within each. The function onlyUnique returns unique values in an array. The problem is, it doesn't work as intended.
arr_lists = [arr_1, arr_2, arr_3, arr_4, arr_5, ...]
for (var list_obj of arr_lists) {
list_obj = list_obj.join().split(',').filter(onlyUnique);
list_obj.sort();
Logger.log(list_obj);
}
The logger results show true (i.e. they are what I am looking for), but the original array is unchanged, although I think it should have been updated.
I've tried assigning the filtered array to a new array... nope.
I know that I could add a thousand lines of code to achieve the results, but that seems silly.
I suspect it's something obvious.
You can simply achieve it by using Set data structure to remove the duplicates and Array.sort() compare function to sort the elements in an array.
Live Demo :
const arr_lists = [[2,3,5,6], [7,2,5,3,3], [1,5,3], [4,7,4,7,3], [1,2,3]];
arr_lists.forEach((arr, index) => {
arr_lists[index] = [...new Set(arr)].sort((a, b) => a -b);
})
console.log(arr_lists);

using slice in an array doesn't affect the template

I have an array availableBoats and I am rendering its elements using the following code snippet:
<app-boat *ngFor="let b of availableBoats" [size]="b.size" [(available)]="b.available" [type]="b.type" ></app-boat>
I was expecting that when I remove one boat from the array using the .slice() function, it won't appear anymore in the template. Am I doing something wrong or this is not the expected behavior in Angular?
At some point, the following code is called. I tested it setting a break-point there and I can see that the boat was removed:
for (let i = 0; i < this.availableBoats.length; i++) {
const b = this.availableBoats[i];
if (b.type === this.selectedBoatType) {
this.availableBoats.slice(i, 1);
return;
}
}
I was expecting that when I remove one boat from the array using the
.slice() function, it won't appear anymore in the template.
Your assumptions are incorrect because slice
(...) returns a shallow copy of a portion of an array into a new array
object selected from begin to end (end not included). The original
array will not be modified.
In order to mutate the array you need to use splice which
(...) changes the contents of an array by removing existing elements
and/or adding new elements
Hence this.availableBoats.slice(i, 1); is not removing any element from this.availableBoats.
In order to do that use this.availableBoats.splice(i, 1);

How can I push a null value into the start of an array?

I have this code that fetches data and puts it into an array:
this.$httpGetTest(this.test.testId)
.success(function (data: ITestQuestion[]) {
self.test.qs = data;
});
It works and populates the array starting with self.test.qs[0].
However many times my code references this array (which contains a list of questions 1...x)
I must always remember to subract 1 from the question number and so my code does not look clear. Is there a way that I could place an entry ahead of all the others in the array so that:
self.test.qs[0] is null
self.test.qs[1] references the first real data for question number 1.
Ideally I would like to do this by putting something after the self.test.qs = and before data.
Push values at start of array via unshift
self.test.qs.unshift(null);
You need to use Splice(), It works like:
The splice() method changes the content of an array, adding new elements while removing old elements.
so try:
self.test.qs.splice(0, 0, null);
Here mid argument 0 is to set no elements to remove from array so it will insert null at zero and move all other elements.
Here is demo:
var arr = [];
arr[0] = "Hello";
arr[1] = "Friend";
alert(arr.join());
arr.splice(1,0,"my");
alert(arr.join());
You can start off with an array with a null value in it, then concat the questions array to it.
var arr = [null];
arr = arr.concat(data);
You could do something like:
x = [null].concat([1, 2, 3]);
Though there isn't anything wrong with doing something like:
x[index-1]
I'd prefer it to be honest, otherwise someone might assume that the index value returned is 0 based.

JS Slice only removes Items when they were in the Constructor

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.

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.

Categories