Remove the last one array like [["1"]] by .splice() , why output = [[]] not []? - javascript

var arr=[["1"]];
arr[0].splice(0,1);
// arr = [[]]
Why I can't remove the last one array to blank ?
I need arr = [] not [[]] when removed and sub-array (array in array) is blank
Demo : http://jsbin.com/ehacof/1/edit
Edit : I just one to remove one by one like
var arr=[["1","2"],["1","2"]];
arr[0].splice(0,1);
arr[0].splice(0,1);
// arr = [[],["1","2"]];
I need arr = [["1","2"]];
Demo : http://jsbin.com/ehacof/9/edit

You are splicing on the first element on the array which is removing "1" from the internal array at arr[0]. This code should remove the first array, not the first element of the first array.
arr.splice(0, 1);
EDIT: If you want to remove that inner array if it's empty then you will need to check it like this.
arr[0].splice(0, 1);
if (arr[0].length === 0)
arr.splice(0, 1);

You removed the "1" from arr[0], so arr[0] is [] and arr contains now an empty array : [[]].
If you want to remove the array itself, splice arr, not arr[0]

var arr=[["1"]];
arr[0].splice(0,1);
if (arr[0].length === 0) {
arr.splice(0,1);
}

Array.splice removes some elements and returns them. Your array of arrays will still stay an array of arrays.
The JSON.stringify converts an empty array: [] to "[]" and thus an empty array of arrays: [[]] becomes "[[]]".
I added some more examples to your jsbin code to illustrate what your code actual does.
var arr=[["1"]];
var elem = arr[0].splice(0,1);
$("body").append(JSON.stringify(arr));
$("body").append(JSON.stringify(elem));
$("body").append(JSON.stringify([[]]));

You cannot use only splice to do the job, i could propose this:
Array.prototype.removeOne = function(i, j) {
if(this[i] == undefined) return this;
this[i].splice(j,1);
if (this[i].length == 0) this.splice(i,1);
return this;
};
Then use arr.removeOne(0,0)
First param is the main array index, the second param is the index of the subarray element to remove.
Edit: There is another way:
var arr=[["1"],["2"]];
arr[0].splice(0,1);
arr=arr.filter(function(ar){return ar.length});

try this in your demo ....
var arr=[["1"]];
arr.splice($.inArray(arr[0],arr));

Related

JS Array.splice return original Array and chain to it

I have a string with values like this a,b,c,d and want to remove a specific letter by index
So here is what I did str.split(',').splice(1,1).toString() and this is (obviously) not working since splice is returning the values removed not the original array
Is there any way to do the above in a one liner?
var str = "a,b,c,d";
console.log(str.split(',').splice(1,1).toString());
Thanks in advance.
You can use filter and add condition as index != 1.
var str = "a,b,c,d";
console.log(str.split(',').filter((x, i) => i != 1).toString());
Another strange solution. Destructure the array, remove the unwanted index, get an object and join the values of it.
var string = "a,b,c,d",
{ 1: _, ...temp } = string.split(',')
console.log(Object.values(temp).join(','));
The alternate way using regex replace
var str = "a,b,c,d";
console.log(str.replace(/,\w+/, ''))
Splice works in place, so oneliner is
const arr = "a,b,c,d".split(','); arr.splice(1,1); console.log(arr.toString());
If you want an string in a oneliner, you have to hardcode the index in a filter
console.log("a,b,c,d".split(',').filter((item, i) => i != 1).toString())
Or two slices (not performant at all)
const arr = "a,b,c,d".split(',')
console.log([...arr.slice(0,1),...arr.slice(2)].toString())

Array.slice using index number contained in another array

I have two arrays.I'm trying to remove some elements from [arr] at index numbers in [removeIndex].
var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
for (let i = 0; i < removeIndex.length;i++){
arr.splice(removeIndex[i],1);
}
console.log(arr)
// output Array(5) [ 1, 1, 0, 1, 1 ]
//expected [ 1,1,1,1,1]
Both the 0's are at arr[2] and arr[3] position and should get removed,however the above code doesnt work.I suspect it has to do with the loop re-arranging the index numbers.Any alternate solution?
You definitely suspect correctly about why this is happening. The easiest way I can think of to do what you're after is to use the not-often-used second argument to the callback function passed to the filter method, which takes an element's index:
arr = arr.filter((elt, index) => removeIndex.indexOf(index) == -1);
You can use Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
and Array.prototype.includes()
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
Pass index as the second parameter to check whether that index includes or not in removeIndex. Return the element only if the current index does not exist in removeIndex array:
var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
arr = arr.filter((i,idx) => !removeIndex.includes(idx));
console.log(arr); //[ 1,1,1,1,1]
I would use filter and come up with this clean code:
var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
var newArr = arr.filter(el => el !== 0);
console.log(newArr);
// [1,1,1,1,1]
As stated in the comments, you mutate the array so the next time you loop through the array it's items will be changed and you won't have the same items at the same indexes. There is a fairly simple solution for your particular example :
var removeIndex = [2,3].sort(); // This won't work with [3,2] for example
var arr = [1,1,0,0,1,1,1];
for (let i = 0; i < removeIndex.length; i++){
arr.splice(removeIndex[i] - i, 1);
}
console.log(arr)
But I'd suggest using an immutable solution with .filter for example, like suggested in the comments

Remove multiple array from other array jquery

I Have 2 array like this
arr = ["9138172", "9138214", "9138238"]
array = ["9138172", "9138238"]
how can I remove values in array from arr?
I want to obtain
arr = ["9138214"]
Maybe I can use splice() ?
You can use Array.forEach() to loop over to the array of items and then check that each item exist in array array. If so use splice(). Use simple function and indexOf() as it will work in old browsers and also in IE.
var arr = ["9138172", "9138214", "9138238"];
var array = ["9138172", "91382142"];
var i = arr.length;
while (i--) {
if (array.indexOf(arr[i]) !== -1) {
arr.splice(i, 1);
}
}
console.log(arr);
You can use .filter() for that.
Here is an example:
var arr = ["9138172", "9138214", "9138238"];
var array = ["9138172", "9138238"];
arr = arr.filter(e => !array.includes(e));
console.log(arr)
The code above just filters the arr array and keeps only elements that are not present in the array. The .includes() function that I've used works on these arrays because they contain strings, if you're dealing with objects, you need to find some other way of checking if array contains the element.
If you want to lodash, this can be easily done by the difference function:
https://lodash.com/docs/4.17.10#difference
import {difference} from 'lodash';
arr = ["9138172", "9138214", "9138238"]
array = ["9138172", "9138238"]
console.log(difference(arr, array));

How to add element in array if it was found?

I use this method to find object in array:
lat arr = [];
found = this.obj[objKey].filter(item => item[internKeyName] == 7047);
arr.push(found);
Problem is that if element was not found it added this as undefined to array arr. How avoid this?
Why it does not find element with key: "subjectId":
let objKey = 7047;
let k = "subjectId";
let v = 7047;
found = this.obj[objKey].filter(item => item[k] == v);
console.log(found);// undefined
You can avoid this by checking the length found before you push it to the array.
lat arr = [];
found = this.obj[objKey].filter(item => item[internKeyName] == 7047);
found.length > 0 && arr.push(...found);
I am using the spread syntax to push each element as its own item to the new array, which I assume that is what you want. You can remove the ... if you want all of the found items to be its own array item.
The function filter won't return undefined, will return an empty array instead (if none elements met the condition).
Problem is that if element was not found it added this as undefined to array arr.
You probably want to find a specific element, so, I recommend you to use the function find if you want only one object rather than an Array with only one index.
lat arr = [];
found = this.obj[objKey].find(item => item[internKeyName] == 7047);
if (found) arr.push(found);
You could push a spreaded array with the wanted objects directly, empty arrays are not spreaded (spread syntax ...).
arr.push(...this.obj[objKey].filter(item => item[internKeyName] == 7047));

javascript does not splice all the element of the array

http://jsfiddle.net/4wKuj/8/
var myarr=new Array("Saab","Volvo","BMW");
console.log(myarr);
for (var i=0; i<myarr.length; i++) {
myarr.splice(i,1);
}
console.log(myarr);
Note: in the real implementation I am not trying to empty the array so plz do not suggest other way of emptying an array.
Why I still see "volvo" in the console log ?
Should not it be removed either , same as other ?
Thank You
What it does :
first iteration, i=0, removes "Saab", => array is ["Volvo","BMW"]
second iteration, i=1, removes "BMW" because this is what you have at index 1
After the first splice:
i = 1
myarr = ["Volvo", "BMW"]
So it will remove "BMW". After the second splice:
i = 2
myarr = ["Volvo"]
And the loop will not continue. Better do it like this:
while (myarr.length > 1) {
myarr.splice(0, 1);
}
before loop, your array looks like
["Saab","Volvo","BMW"]
after first iteration of loop you delete first element of array, and now array looks like
["Volvo","BMW"]
during second iteration your "i" variable has '1' (one) value that corresponds to second element of array, in other words you say:
delete in ["Volvo","BMW"] array element with index '1'
If you remove an item from the array, you also need to adjust the index value, f.ex:
var myarr=new Array("Saab","Volvo","BMW");
for (var i=0; i<myarr.length; i++) {
myarr.splice(i--,1);
}
Tip: If you are using a loop remove items from an array based on it’s value, you can use other methods, f.ex Array.filter:
myarr = myarr.filter(function(val) {
return val !== 'Volvo'
});
Array.indexOf also comes to mind.

Categories

Resources