Javascript splice is removing everything but the element requested - javascript

I have a pretty simple script that takes content from an input box, makes an array out of it, removes a desired element, and spits back the text.
I'm trying to use "splice()" to remove the item but it removes everything BUT that one item:
var listOfTitles = $('.title-list').val();
var arrayOfTitles = listOfTitles.split(',');
var updatedTitles = arrayOfTitles.splice(2,1);
$('.title-list').val(updatedTitles.join());
for example if I have this:
test1,test2,test3,test4
I can turn it into an array. I want to removed "test3" and output "test1,test2,test4". The problem is, it's returning "test3" not removing it.
jsfiddle of what's happening: http://jsfiddle.net/C95kN/

Splice() modifies the array in place and returns an array with the elements you remove.
What you want is arrayOfTitles not updatedTitles
See working fiddle: http://jsfiddle.net/C95kN/1/

splice changes the passed array and returns the removed elements. Simply do
arrayOfTitles.splice(2,1);
$('.title-list').val(arrayOfTitles.join());
Note that I supposed the slice instead of splice was a typo.

Related

insertBefore function for arrays and/or HTMLCollections?

Does there exist a function in vanilla JavaScript or jQuery that operates similarly to Node.insertBefore(), but for arrays and/or HTMLCollections?
An example could look something like:
var list = document.getElementsByClassName("stuff");
var nodeToMove = list[0];
var otherNode = list[4];
list.insertBefore(nodeToMove, otherNode);
Basically I'm trying to perform insertBefore() without manipulating the actual DOM, as I want the changes to only be applied to the DOM under certain conditions. If those conditions are met, then I would perform insertBefore() on the actual nodes.
To clarify, I'm looking for a function that would insert an element before a target element at a given index in an array, not necessarily at a given index. Examples I've seen using splice() usually insert an element at a given index, which sometimes puts the element before the target element, and sometimes after, depending on where the element to be moved originally was in the array. I'm looking for something that would reliably put the element to be moved before the target element.
HTMLCollection does not have an insertBefore method. jQuery can apply any jQuery methods both to a single element being selected, as well as many.
https://api.jquery.com/insertBefore/
There is no single method to do this in one step, but there doesn't need to be. If you convert the collection to an Array, you can call the Array.prototype.splice() method to achieve the same result.
Here's an example:
let ary = [1,2,3,4,5];
// Swap 2 and 3
// Start at the 3rd item and remove one item (3).
// Store the removed item
let removed = ary.splice(2,1);
// Start at the second item, don't remove anything, insert the removed
// item at that position
ary.splice(1,null,removed[0]);
// Log the result
console.log(ary);
And, with that knowledge, you can create your own more easily callable function:
let ary = [1,2,3,4,5];
function insertBefore(ary, newItem, target){
ary.splice(target,null,newItem);
}
// Insert 999 before the 3rd array item
insertBefore(ary,999,2)
console.log(ary);
You need to get the index you want, then use Array.splice.
Myself I would do something like this :
const myArr = ['Aurore', 'Dimitri', 'Alban', 'Frédéric'];
const insertBeforeThis = 'Alban';
const eltToInsert = 'Laura';
const index = myArr.findIndex(name => name === insertBeforeThis);
myArr.splice(index, 0, eltToInsert);
Please feel free to try it out in your browser's console. Note i used const for my array, as it fixes the type of the variable as an array but allow me to manipulate it.
MDN: Array.prototype.findIndex()
stackoverflow: How to insert an item into an array at a specific index (JavaScript)?
Have a happy coding time!

does array.shift() delete the array?

i have an array that has one element and i want to use proarray.shift();
var proarray=[];
proarray[0]=1;
//...
proarray.shift();
//...
proarray[i]=5;
but when i do, it stops the program.
does it delete the array?
if it does, what should i do to prevent that? cuz i need that array for later.
and also i tried to use
var proarray=[];
proarray[0]=1;
//...
array.splice(0,1);
//...
proarray[i]=5;
but it didn't work.
what should i do?
From the docs.
The shift method removes the element at the zeroeth index and shifts
the values at consecutive indexes down, then returns the removed
value. If the length property is 0, undefined is returned.
The program is likely stopping because you are accessing an index in the array that no longer exists.

How to remove the last element from JQuery array?

I want to select some DOM elements into a clone object then I want to remove the last item. After trying it in Chrome console I see that clone's length does not decrease.
Example from Chrome console:
crumbs = $("span",$("div[style='width:390px;background-color:white;'")[0]).clone();
jQuery.fn.jQuery.init[114]
crumbs.last().remove()
[​…​​]
crumbs.length
114
As you see, length is still 114 elements. What am I missing?
crumbs.last().remove() removes the last matched element from the DOM, it doesn't remove it from the jQuery object.
To remove an element from the jQuery object¹ use slice:
var withoutLastOne = crumbs.slice(0, -1);
¹ Actually this will create a new object that matches one less element instead of modifying your existing object. You will usually not care about the distinction, but should be aware of it.
To remove last element from the array you can use below code too.
var arr = ["item1", "item2", "item3", "item4"];
arr.pop();
Demo
As people said, .remove() removes the element from the DOM. Another option than using slice on the final result is to use jquery's filtering before cloning the element:
crumbs = $("span",$("div[style='width:390px;background-color:white;'")[0]).not(':last').clone();

When array length = 0, it stills shows as 1

I am dealing with an array that I want to delete an object from and return the new length of the array. For all other numbers, it works - but for one item, it does not. Not sure how to fix it so that the array length is 0 after the only object is deleted. My code is below:
Here's an example where I had one object in the 'player' array:
function deletecamera(id){
alert('before the splice, player length =' + player.length); //returns 1
delete player.splice((id),1);
i=0;
for (i=0;i<player.length;i++){
player.id=i;
}
alert('after reassigning, player length =' + player.length); // still returns 1?!
refreshlist();
}
the delete keyword doesn't remove the object from the array, it sets its value to undefined, so the size of the array stay the same.
See example here: http://jsfiddle.net/up5XX/
If you want to remove the first element from the array player using .splice, you can do this:
player.splice(0, 1);
yeah, thinking a bit more about this, I bet it will work if you change this line:
delete player.splice((id),1);
to
player.splice((id),1);
some weird codes there.
An array in JS is an object that can hold multiple [elements]. But just like with any other JS object you can add more members to it by just saying myArrayName.someMemberName = something. This will not be 'in' the array as if it was an element. This is even the JS poor mans way for an 'associative array’. This is what you are doing now with the .id = ...
You need to change
player.id = i;
into something like
player[i].id = i;
(or something like it. Don't know what the goal is there. I guess you want to reorder all Id's after deleting one in between.)
futhermore ... change the splice line to just this:
player.splice(id,1);
and remove the extra line with just:
i=0;
But I now realise these all are tips but no solution to your problem.
Can you please add
alert('trying to remove id ' + id);
and confirm that you do at least once try to delete id 0 ?

Javascript "shift" versus "splice" - are these statements equal?

I just want to confirm if the following two Javascript statements produces the same results, as it seems to me:
First:
var element = my_array.splice(0,1)[0];
Second:
var element = my_array.shift();
I want to substitute the first by the second, in my own code, to improve readability. Can I do this?
They will have the same effect, yes. splice(0, 1) will remove the first element from my_array and return a new array containing that element. shift will do the same, but return the element itself, not an array.
shift is more readable (in my opinion) and is also significantly faster (in Chrome at least):
Both lines of code remove the first element from the array, and return the removed element, they are both supported in all major browsers.
You should use the second one, and the code will be more readable indeed.
shift returns the element that was removed, splice returns an array of elements that were removed.
that being said, the two statements do the same thing and i would agree that the second is more readable.
splice will return as an array but not remove data from the object instead make a copy
shift just give one data from front and also remove from object
For example,
const object = {1}
object.slice(); // return [{1}]
//object will be : {1}
object.shift(); // return {1}
//object will be : {} as shift remove the front data

Categories

Resources