I have an array this way :
var array = [ [1,2] , [2,2,2] , 3 , [3,4] ];
So I want to use indexOf to splice an element.
Example :
var index = array.indexOf( [2,2,2] );
array.splice(index, 1)
Expect =>
array = [ [1,2] , 3 , [3,4] ]
But the problem is that index return -1 (false value).. How to fix that?
The problem is, you have two arrays with the same primitives, but the arrays are not equal.
The comparing works with the object and not with the values inside.
console.log([2, 2, 2] === [2, 2, 2]); // false var array = [2, 2, 2]; console.log(array === array); // true
If you search for the same array with the same reference to the object, then you get the right index.
var search = [2, 2, 2], // array to serach for array = [[1, 2], search, 3, [3, 4]], // array with search array index = array.indexOf(search); // get the index array.splice(index, 1); console.log(array); // [[1, 2], 3, [3, 4]]
In ES5, you could search for the index and use a stringified version of the search object for checking with Array#some
.
var array = [[1, 2], [2, 2, 2], 3, [3, 4]], search = [2, 2, 2], index = -1; array.some(function(a, i) { if (JSON.stringify(a) === JSON.stringify(search)) { index = i; return true; } }); if (index !== -1) { array.splice(index, 1); } console.log(array);
ES6 with Array#findIndex
var array = [[1, 2], [2, 2, 2], 3, [3, 4]], search = [2, 2, 2], index = array.findIndex(a => JSON.stringify(a) === JSON.stringify(search)); if (index !== -1) { array.splice(index, 1); } console.log(array)
If you can use a library, you can use the lodash
library that exposes a reject
function.
Here is a snippet:
var array = [ [1,2] , [2,2,2] , 3 , [3,4] ]; var result = _.reject(array, [2,2,2]); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
var array = [[1, 2], [2, 2, 2], 3, [3, 4]];
var index = array.findIndex(a => JSON.stringify(a) === "[2,2,2]");
alert(index);
if (index > -1) {
array.splice(index, 1);
}
alert(array)
Hope this helps!
indexOf doesn't work because it uses strict equality, so you can't find an array within an array unless you have a reference to the array you're trying to find.
As an alternative, you can use a plain old ed 3 for loop and compare stringified values:
var array = [ [1,2] , [2,2,2] , 3 , [3,4] ]; function findIndex(arr, value) { for ( var i=0, value=String(value), iLen=arr.length; i<iLen; i++) { if (String(arr[i]) == value) return i; } return -1; } console.log(findIndex(array, [2,2,2])); // 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.