jQuery get contents (length) of an integer array - javascript

I have an integer array which looks like this:
var _SingleScannedItemIds = [];
At some point I push some items inside the array itself like following:
_SingleScannedItemIds.push(checkbox_value);
Now my question here is:
How do I know if the array contains anything inside of it?
How do I remove integer numbers from it, based on which parameter?
Can someone help me out? I'm using jQuery...

How do I know if the array contains anything inside of it?
if(_SingleScannedItemIds.length == 0)
How do I remove integer numbers from it, based on which parameter?
_SingleScannedItemIds.splice(pos, 1)
What the above does is it removes 1 element from the position pos.
EDIT
delete _SingleScannedItemIds[pos]
Makes the _SingleScannedItemIds[pos] = undefined and then you can reassign it later with ex. _SingleScannedItemIds[0] = "apple". assuming pos = 0

jQuery Has nothing to do here.
Just use array.length array.splice()

Splice(index, numberOfElementsToRemove)

To get the length of an array:
var array = [0, 1, 2, 4];
console.log(array.length);
Removing items from an array is done by the key:
function remove(array, element) {
const index = array.indexOf(element);
array.splice(index, 1);
}
var array = [0, 1, 2, 4];
remove(array, 1); //removes number 1
console.log(array);

Related

javascript splice method removing elements from end

I am trying to remove 2 elements from end using splice method
This is what I am tryed
const arr = [3,4,5,6,7];
arr.splice(-1, 2)
I am expecting arr to be [3,4,5] but arr value is [3,4,5,6]
wanted to understand why it's behaving like this
From MDN
start
The index at which to start changing the array. If greater than the
length of the array, start will be set to the length of the array. If
negative, it will begin that many elements from the end of the array.
(In this case, the origin -1, meaning -n is the index of the nth last
element, and is therefore equivalent to the index of array.length -
n.) If array.length + start is less than 0, it will begin from index
0.
index -1 means from the last element so in our case, only the last element will be deleted.
You just start by the last index of the array and remove two items.
The result is an array without 7.
// -1 index
const arr = [3, 4, 5, 6, 7];
arr.splice(-1, 2);
console.log(arr);
The easiest way to do this will be to use arr.length
const arr = [3,4,5,6,7];
arr.splice(arr.length - 2)
console.log(arr)
First param tells to splice from which index it should delete all elements
const arr = [3,4,5,6,7];
const itemsToDelete = 2;
arr.splice(arr.length - itemsToDelete, itemsToDelete)
console.log('arr', arr);

array.splice() returns the item I want to eliminate rather than the array minus the item

I'm trying to remove an item from an array using the indexOf() with splice() technique suggested. This is what's happening
let someArray: string[] = [first, second, third, fourth, fifth, sixth];
let newArray: string[] = someArray.splice(3, 1);
console.log(newArray);
//deisred result = [first, second, third, fifth, sixth]
//result I'm getting = [fourth]
That's not what virtually every article I've come across says should happen. Can someone shed light on this?
UPDATE
I discovered this problem in my code when I was only ghetting 1 result where I was expecting more and tracked it back to this point.
Because when you splice an array you are mutating it, which means you are changing the original array. You're storing the result (the element you're splicing from the array) within the "newArray" variable that you have created here. So this:
var arr = [1, 2, 3, 4];
var mine = arr.splice(1, 1);
console.log(mine);
console.log(arr);
would return the original ray minus index one if we print arr to the console, and will return [2] if we print mine to the console. To get the output you're expecting, you would have to perform a different operation such as iterating through the array and utilizing splice differently. Here is an example:
var arr = [1, 2, 3, 4];
var mine = [];
for(var i = 0; i < arr.length; i++) {
if(i !== 3) {
mine.push(arr[i]);
}
}
Now I am not mutating the original array, and I am simply pushing the elements to a new array.
But if you want to simply mutate the original array and not store the new array in some sort of variable you can simply splice the original array:
var arr = [1, 2, 3, 4];
arr.splice(3, 1);
console.log(arr);
However, if you are passing it to a function, i'd probably not mutate an array outside of the function, and i'd simply return a value and store that value in a new variable:
var arr = [1, 2, 3, 4];
function deleteIndex(ar, i) {
var a = [];
ar.forEach(function(elt, index) {
if(index === i) {
}
else {
a.push(elt);
}
});
return a;
}
var newArr = deleteIndex(arr, 3);
console.log(newArr);
This way you can delete any index, or pass a function and criteria that you would want to use to determine if an index should be deleted, without changing to top-level structure of your original array by utilizing functional programming. There are also some function in the underscore module that can help you if that's the case.

Javascript: How to pass an array with specific index to a function?

Let say I have an array:-
var arr = [0,1,2,3,4]
I need to pass only "1" and "4" to function below
function func1(onlyArray){
//Do Stuff...
}
I have tried both but both also dont work
func1(arr[1,4])
func1(arr[[1],[4]])
Can anyone show me the right way or give me some keyword?
You can use this:
func([arr[1], arr[4]])
We are taking the elements at index 1 and 4 of the array arr and creating a new array with those elements. Then we pass that newly created array to func.
If you need a single array instead of 2, use this:
var arr = [0,1,2,3,4];
function func1(onlyArray){
//Do Stuff...
console.log(onlyArray); // [1, 4]
}
func1(arr.filter((item,index) => index === 1 || index === 4));
So using your array:
var arr = [0,1,2,3,4];
and your function:
function myFunction(newArr){
//Do stuff
console.log(newArr);
};
You can wrap the array indexes you want to use inside of their own array when you call the function, like the following:
myFunction([arr[1], arr[4]]); //Output is [1, 4]

Replacing Array element with same index in javascript

I have an Array like
var myArray = new Array;
I have to push some elements to array in such a way that the elements will be replaced with same index.
Example :
myArray.push(1);
myArray.push(2);
myArray.push(3);
so now
myArray[0] = 1
myArray[1] = 2
now when i will push element 3 then
myArray[0] will be replaced with 3 and myArray[1] will be replaced with 1 and the element 2 will be removed.
It will continue according to the number of elements pushed...
Can any body help me with this requirement...
push adds to the end of an array. If you want to add a value to the beginning of an array you can use unshift.
myArray.unshift(3);
You can then use pop to remove the last element:
arr.pop();
DEMO
However, what you might need, given that you need to remove the same number of elements from an array that you add is a function that uses concat and slice instead:
function pusher(arr, add) {
return add.concat(arr).slice(0, arr.length);
}
var arr = [1, 2, 3, 4];
var arr = pusher(arr, [5, 6]); // [5, 6, 1, 2]
DEMO
I think you need something in the lines of:
myArray.unshift(element);
myArray.pop();
Explanation:
unshift: inserts the element on position 0 and moves all other elements one position to the right
pop: removes last element from array

Why does adding [0] after the delete count in splice() return just a number?

First of all sorry for the long title, I really didn't know how to word it better.
In the middle of solving _.shuffle in underscore, I encountered the use of splice. Here is my original code :
shuffle = function(array) {
var shuffledArray = [];
var total = array.length;
var copiedArray = array.slice();
while (total){
var randomNum = Math.floor(Math.random() * total);
shuffledArray.push(copiedArray.splice(randomNum,1));
total--;
}
return shuffledArray;
};
var originArray = [1, 2, 3, 4];
console.log(shuffle(originArray));
However after testing just I realized it will return each value inside a [ ], instead of just the value.
i.e.
[ [ 4 ], [ 3 ], [ 1 ], [ 2 ] ]
//instead of [ 4, 3, 1, 2]
When I changed this line (added '[0]' after the deleteCount in splice)
shuffledArray.push(copiedArray.splice(randomNum,1));
into this
//edited
shuffledArray.push(copiedArray.splice(randomNum,1)[0]);
the return array that I get is what I wanted, which is
[ 3, 1, 2, 4 ] //values are not in [ ]
Can someone explain how adding [0] after splice() makes the value not return in [ ] or why not having [0] does?
splice returns an array. When you push an array into an array, you get an array of arrays. By adding the [0], you push the first element of the array instead. This is no Javascript weirdness - it's perfectly reasonable.
As I suspected and was confirmed in the comments, you were using copiedArray.splice(randomNum,1)[0], not copiedArray.splice(randomNum,1[0]).
EDIT: That was the original question, and it was since edited.
And since splice returns an array (in your case, an array with one number), taking the first element of the array achieves exactly what you wanted.
Splice returns an array of the deleted elements. By adding [0] you are effectively selecting the first item in the returned array.
Try not to reinvent the wheel !
http://php.net/manual/fr/function.shuffle.php
If you really want to, try this in your while:
while (total){
var randomNum = Math.floor(Math.random() * total);
ShuffledArray[] = array[randomNum]; //add an item to next pos
unset(array[randomNum]); //remove the item added
array = array_values(array); //reindex array
total--;
}
Best of luck !

Categories