using slice in an array doesn't affect the template - javascript

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);

Related

How to remove an element from array in javascript without making a new?

I read many answers but I didn't understand how to use splice in this case..
Suppose i have an array named alphabets like - ["a","b","c","d","e"] and i have to remove c from it. I dont want to create another array with c removed instead i want to update the same list each time an item is removed just like remove method in python. I know the index also so it can be like alphabets.remove[3]...to remove c. Please help me i am beginner.
Actually it would be better if there's a way that i can remove using just index number cause the names in array are very tough. Any help is appreciated
To modify the array rather than creating a new one, as you said you'd want the splice method. You pass the index of the item to remove, and the number of items to remove at that index:
const index = theArray.indexOf("c");
theArray.splice(index, 1);
Live Example:
const theArray = ["a","b","c","d","e"];
const rememberArray = theArray; // Just so we can prove it's the same array later
const index = theArray.indexOf("c");
theArray.splice(index, 1);
console.log(theArray);
console.log("Same array? " + (rememberArray === theArray));

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.

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

JavaScript - Get all but last item in array

This is my code:
function insert(){
var loc_array = document.location.href.split('/');
var linkElement = document.getElementById("waBackButton");
var linkElementLink = document.getElementById("waBackButtonlnk");
linkElement.innerHTML=loc_array[loc_array.length-2];
linkElementLink.href = loc_array[loc_array.length];
}
I want linkElementLink.href to grab everything but the last item in the array. Right now it is broken, and the item before it gets the second-to-last item.
I’m not quite sure what you’re trying to do. But you can use slice to slice the array:
loc_array = loc_array.slice(0, -1);
Use pathname in preference to href to retrieve only the path part of the link. Otherwise you'll get unexpected results if there is a ?query or #fragment suffix, or the path is / (no parent).
linkElementLink.href= location.pathname.split('/').slice(0, -1).join('/');
(But then, surely you could just say:)
linkElementLink.href= '.';
Don't do this:
linkElement.innerHTML=loc_array[loc_array.length-2];
Setting HTML from an arbitrary string is dangerous. If the URL you took this text from contains characters that are special in HTML, like < and &, users could inject markup. If you could get <script> in the URL (which you shouldn't be able to as it's invalid, but some browser might let you anyway) you'd have cross-site-scripting security holes.
To set the text of an element, instead of HTML, either use document.createTextNode('string') and append it to the element, or branch code to use innerText (IE) or textContent (other modern browsers).
If using lodash one could employ _.initial(array):
_.initial(array): Gets all but the last element of array.
Example:
_.initial([1, 2, 3]);
// → [1, 2]
Depending on whether or not you are ever going to reuse the array you could simply use the pop() method one time to remove the last element.
linkElementLink.href = loc_array[loc_array.length]; adds a new empty slot in the array because arrays run from 0 to array.length-1; So you returning an empty slot.
linkElement.innerHTML=loc_array[loc_array.length-2]; if you use the brackets you are only getting the contents of one index. I'm not sure if that is what you want? The next section tells how to get more than one index.
To get what you want you need for the .href you need to slice the array.
linkElementLink.href = loc_array.slice(0,loc_array.length-1);
or using a negative to count from the end
linkElementLink.href = loc_array.slice(0,-1);
and this is the faster way.
Also note that when getting to stuff straight from the array you will get the same as the .toString() method, which is item1, item2, item3. If you don't want the commas you need to use .join(). Like array.join('-') would return item1-item2-item3. Here is a list of all the array methods http://www.w3schools.com/jsref/jsref_obj_array.asp. It is a good resource for doing this.
.slice(number you want)
if you just want the first 4 elements in an array its array.slice(3)
doing a negative number starts from the end of the array

Categories