How can I completely remove an object from an array in Javascript? - 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}));

Related

How can I make sure Javascript array containing values with certain character remain unaltered, while I work on it?

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 .

Remove element from jQuery object

I have a jQuery object that is created via jQuery .find() as seen below...
var $mytable= $('#mytable');
var $myObject = $mytable.find("tbody tr");
This works great and creates a jQuery object of all the tr elements in the tbody. However, as I'm looping over the data, I need to be able to remove parts of the object as I go. For instance, if the above call returns a jQuery object named $myObject with a length of 10, and I want to remove the index 10, I thought I could just do $myObject.splice(10,1) and it would remove the element at index 10. However this doesn't seem to be working.
Any ideas why? Thank you!
UPDATE
I basically just want to be able to remove any element I want from $myObject as I loop through the data. I know it's zero based (bad example above I guess), was just trying to get my point across.
UPDATE
Okay, so I create the object using the find method on the table and at it's creation it's length is 24. As I loop over the object, when I hit an element I don't want I tried to use Array.prototype.splice.call($rows,x,1) where x represents the index to remove. Afterwards when I view the object in the console, it still has a length of 24.
Use .not() to remove a single element, then loop through the jQuery object at your leisure:
var $myObject = $mytable.find('tbody tr').not(':eq(9)'); // zero-based
http://jsfiddle.net/mblase75/tLP87/
http://api.jquery.com/not/
Or if you might be removing more than one:
var $myObject = $mytable.find("tbody tr:lt(9)");
http://jsfiddle.net/mblase75/9evT8/
http://api.jquery.com/lt-selector/
splice is not part of the jQuery API, but you can apply native Array methods on jQuery collections by applying the prototype:
Array.prototype.splice.call($myObject, 9, 1); // 0-index
You can also use pop to remove the last item:
Array.prototype.pop.call($myObject);
This should also give you a correct length property.
splice is an array method, not a jQuery object method.
Try slice
Javascript uses zero-based arrays. This means that the final item in the array (i.e. the 10th item) will be at index 9.
$myObject[9]
So you need something like this:
$myObject.splice(9, 1);
This will remove the element from your existing array, and also return it.
You could also use filter :
var $myObject = $mytable.find("tbody tr").filter(':lt(9)');
You can use .remove to remove an element from the DOM.
So to remove the element at index 9 of the $myObject array, use:
$myObject.eq(9).remove();
If you want to keep the element that you are removing, you can also do:
var removedElement = $myObject.eq(9);
removedElement.detach();

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 to add key/value pair in to array dynamically

I want to add an array dynamically using jquery. How can i do that.(or)
I want to push the elements in to array like this.
var array = [{"question":"1","answer":"2"}];
i want to do that dynamically using for loop i mean
initially i will add
array.push({"question":"1"});
then array.push({"answer":"2"});
but I want the elements to in the same array[0] element
but it is taking as array[0],array[1]
How can I do that. I am using for loop to add the elements in to an array.
If you are pushing an answer immediately after, can you not do something like
array[index] = { "question" : array[index].question, "answer": 2 };
If not you will have to find some other way of finding the index where the question was pushed and then
Just note that array.push always adds a new object to the array, and does not update it.

Converting an array to a string in Javascript

I have a multi-dimensional array like this:
1 2 3
4 5 6
Now I need to convert this array into a string like 1,2,3;4,5,6.
Can any one suggest how to do this, please?
simply use the join method on the array.
> [[1,2,3],[4,5,6]].join(';')
'1,2,3;4,5,6'
It's lucky that you simply don't have to consider how the apply the join method on the inner lists, because a list is joined by comma by default. when a list is coerced into a string, it by default uses commas to separate the items.
As it was already mentioned by qiao, join() is not recursive.
But if you handle the recursion yourself you should acquire the desired result, although in a rather inelegant way.
var array = [[1,2,3],[5,6,7]];
var result = [];
array.forEach(
function(el){
result.push(
el.join(",")
);
});
result.join(";");
If you need to serialize an array into a string and then deserialize it later to get an array from the string you might want to take a look at JSON:
http://www.openjs.com/scripts/data/json_encode.php
Try this:
array.toString();
See here for reference: http://www.w3schools.com/jsref/jsref_tostring_array.asp
See answer by qiao for a much nicer approach to multidimensional arrays like this.

Categories