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
Related
I want to create array once and then just push values to it with any index , but i get Cannot read property 'push' of undefined error
I have following scenario
var neg = [];
I want to use push randomly with any index
neg[0].push([1,2]);
or
neg[22].push([1,2]);
right now I want to define manually like neg[0] = []; , Is there any one way where i can just push to any index i want ?
Here's a quick way to do exactly what you want.
var arr = [];
(arr[0]=[]).push([1,2]);
console.log(arr)
Also it's safer to check if an array already exists at this index, otherwise it will be replaced with an empty array – the above code will replace the array with an empty one if it already exists.
// creates an array at index 0 only if there's no array at this index.
// pushes an array of [1, 2] to the existing array at 0 index
// or the newly created empty one.
(arr[0] || (arr[0] = [])).push([1, 2]);;
var arr = [];
arr[0] = [1];
(arr[0]||(arr[0]=[])).push(2,3);
console.log(arr)
Push will add elements to the end of an array. For example:
var neg = [];
neg.push(3); //this will add the number 3 to the end of your array
The problem here is your trying to add a value to an undefined element:
var neg = [];
neg[0].push([1,2]); // <-- neg[0] is not defined at this moment, and you're treating it as an array object.
If you define your elements as an array, you will not get such an error:
var neg = [];
neg[0] = [];
neg[22] = [];
neg[0].push([1,2]);
neg[22].push([1,2]);
Alternatively (and this is probably what you're probably looking for), you can set the value for any element of your array with the desired index:
var neg = [];
neg[0] = [1,2];
neg[22] = [1,2];
You are going to have to set it to an empty array before you can push it.
neg[0] = neg[0] || []
neg[0].push([1,2]);
You can specify how large the array will be if you know ahead of time, for example var neg = new Array(40); will create a new array with 40 undefined elements.
Once that is created, you can change the value at any index as long as 0 <= index <= 39.
You can use array.splice(your_index, 0, your_element); to push an element into an array at the given index.
I'm trying to complete a problem that involves removing the last item of an array without using the built-in .pop function. Here is the full problem...
Write a function which accepts an array.
The function should remove the last value in the array and return the value removed or undefined if the array is empty.
Do not use the built in Array.pop() function!
Example:
var arr = [1, 2, 3, 4];
pop(arr); // 4
I figured out how to grab the last number with the following code but this obviously doesn't solve the problem.
function pop (array){
for (i=array.length-1; i>array.length-2; i--){
array = array[i]
} return array
}
pop ([1,2,3,4])
Thanks in advance!
A much simpler solution is to just decrease the length of the array by one. No need to create a second array.
function pop (array){
let last = array[array.length-1]; // Store last item in array
array.length = array.length > 0 ? array.length - 1 : 0; // Decrease length
return last; // Return last item
}
// Test function
function logger(ary){
console.log("Original array: " + ary.join(", "), "\n\tItem popped off: " + pop(ary), "\n\tArray contents now: " + ary.join(", "));
}
// Tests
var ary = [1,2,3,4]; logger(ary);
var ary = ["red", "white", "blue", "green"]; logger(ary);
var ary = ["onlyItem"]; logger(ary);
var ary = []; logger(ary);
var ary = [false]; logger(ary);
It seems like simple is better in this case:
const example = [1,2,3,4];
function pop(arr) {
return arr && arr.splice(-1)[0]
}
console.log(pop(example))
console.log(pop(example))
console.log(pop(example))
console.log(pop(example))
console.log(pop(example))
// edge case: should it return undefined or should it throw?
console.log(pop())
EDIT: This includes a null and empty check.
var array = [1, 2, 3, 4, 5];
function pop(array) {
return array && array.splice(-1)[0]
}
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(pop(array));
console.log(array);
I think what you are looking for is Array.prototype.slice(). You can use the length property of the array to determine whether it is empty and then return the last entry using slice.
const example = [1,2,3,4];
const emptyExample = [];
const pop = group => group.length > 0
? group.slice(group.length - 1)[0]
: undefined;
const answers = [ pop(example), pop(emptyExample) ];
console.log(answers);
Edit from comment
Example should remove from the array while returning last entry so Array.prototype.splice is probably the better function here.
const example = [1,2,3,4];
const emptyExample = [];
const pop = group => (Array.isArray(group) && group.length > 0)
? group.splice(group.length - 1, 1)[0]
: undefined;
const initialExample = [ ...example ];
const answers = [
pop(example),
pop(emptyExample),
{ initialExample, updatedExample: example, emptyExample }
];
console.log(answers);
Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])
The splice() method changes the contents of an array by removing existing elements and/or adding new elements.
...
Return value: An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
What this means is that so long as the input to the function is an instance of Array, we can call Array#splice(-1) to remove the last element. If there are no elements, this will return an empty array. Because we will always be getting either an array with one element or an empty array, we can access the first element using [0]. If the array is empty, this will be undefined.
So, check that that input is an array, then return Array#splice(-1)[0] if it is or undefined if it is not.
function pop(input) {
let output;
if(input instanceof Array) {
output = input.splice(-1)[0]
}
return output
}
function test(input) {
console.log({
before: input && Array.from(input),
popped: pop(input),
after: input
})
return test
}
test( [ 1, 2, 3, 4 ] )( [ 1 ] )( [ ] )( )( [ , , , ] )
You could use Array.splice()
function pop(arr) {
return arr.splice(-1)[0];
}
This will delete the last item in the array and return it.
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));
I create an array with let arr = new Array(99999) but I don't fill it up to arr.length which is 99999, how can I know how much actual, non undefined elements do I have in this array?
Is there a better way than to look for the first undefined?
You could use Array#forEach, which skips sparse elements.
let array = new Array(99999),
count = 0;
array[30] = undefined;
array.forEach(_ => count++);
console.log(count);
The same with Array#reduce
let array = new Array(99999),
count = 0;
array[30] = undefined;
count = array.reduce(c => c + 1, 0);
console.log(count);
For filtering non sparse/dense elements, you could use a callback which returns for every element true.
Maybe this link helps a bit to understand the mechanic of a sparse array: JavaScript: sparse arrays vs. dense arrays.
let array = new Array(99999),
nonsparsed;
array[30] = undefined;
nonsparsed = array.filter(_ => true);
console.log(nonsparsed);
console.log(nonsparsed.length);
The fastest & simplest way to filter items in an array is to... well... use the .filter() function, to filter out only the elements that are valid (non undefined in your case), and then check the .length of the result...
function isValid(value) {
return value != undefined;
}
var arr = [12, undefined, "blabla", ,true, 44];
var filtered = arr.filter(isValid);
console.log(filtered); // [12, "blabla", true, 44]
I have an array that looks like this:
var locationsArray = [['title1','description1','12'],['title2','description2','7'],['title3','description3','57']];
I can't figure out what type of array this is. More importantly, I'm gonna have to create one based on the info there. So, if the number on the end is greater than 10 then create a brand new array in the same exact style, but only with the title and description.
var newArray = [];
// just a guess
if(locationsArray[0,2]>10){
//add to my newArray like this : ['title1','description1'],['title3','description3']
?
}
How can I do it?
Try like below,
var newArray = [];
for (var i = 0; i < locationsArray.length; i++) {
if (parseInt(locationsArray[i][2], 10) > 10) {
newArray.push([locationsArray[i][0], locationsArray[i][1]]);
}
}
DEMO: http://jsfiddle.net/cT6NV/
It's an array of arrays, also known as a 2-dimensional array. Each index contains its own array that has its own set of indexes.
For instance, if I retrieve locationsArray[0] I get ['title1','description1','12']. If I needed to get the title from the first array, I can access it by locationsArray[0][0] to get 'title1'.
Completing your example:
var newArray = [];
// just a guess
if(locationsArray[0][2]>10){
newArray.push( [ locationsArray[0][0], locationsArray[0][1] ] );
}
throw that in a loop and you're good to go.
It's an array of arrays of strings.
Each time there is this : [], it defines an array, and the content can be anything (such as another array, in your case).
So, if we take the following example :
var myArray = ["string", "string2", ["string3-1", "string3-2"]];
The values would be as such :
myArray[0] == "string"
myArray[1] == "string2"
myArray[2][0] == "string3-1"
myArray[2][1] == "string3-2"
There can be as many levels of depth as your RAM can handle.
locationsArray is an array of arrays. The first [] operator indexes into the main array (e.g. locationsArray[0] = ['title1','description1','12']) while a second [] operation indexes into the array that the first index pointed to (e.g. locationsArray[0][1] = 'description1').
Your newArray looks like it needs to be the same thing.
It's an array of array.
var newArray = [];
var locationsArray = [
['title1','description1','12'],
['title2','description2','7'],
['title3','description3','57']
];
for(i = 0; i < locationsArray.length; i++) {
if (locationsArray[i][2] > 10) {
newArray .push([locationsArray[i][0], locationsArray[i][1]]);
}
}
console.log(newArray );