Splice items from array considering indexes from another array - javascript

I have an array input and another array indexes. I want to remove item from array input whose index is provided in indexes array.
I have tried it using array.splice in for loop but as item is being removed in each iteration, indexes of other items are being changed.
JavaScript:
var array = [10, 11, 12, 13, 14, 15];
var indexes = [0, 1, 2, 3, 4, 5];
indexes.forEach(function(item) {
array.splice(item, 1);
});
console.log(array);

You can utilize Array.prototype.filter and do the following:
var array = [10, 11, 12, 13, 14, 15];
var indexes = [0, 1, 2, 3, 4, 5];
array = array.filter(function(x, i) {
return indexes.indexOf(i) === -1;
});
console.log(array);

Here you are using forEach loop which give you the item as first argument and the index on second one, so as per my understanding what you want to do can achieve by this, try this hope this solve your problem :)
indexes.forEach(function(item, index) {
array.splice(index, 1);
});

Sort the indexes array from high to low, then spice will only change the index of the numbers you have already removed

Related

forEach seems to be working for push() function but didn't work for pop() in JavaScript. can someone tell me what I am doing wrong

//code1
let a= [1, 3 , 4, 6];
[7, 8 , 9].forEach(l => a.push(l));
console.log(a);
// [1, 3, 4, 6, 7, 8, 9 ]
1.it worked for push() function
//code2
let a= [1, 3 , 4, 6];
a.forEach(l => a.pop(l));
console.log(a);
//[ 1, 3 ]
2. didn't work for pop() though
Javascript Array.pop() removes the last element from the array and returns that.
Example:
var arr = [1,2,3]
arr.pop(); // returns 3
Reference
If you want to remove a element with specific value than try something like:
var arr = [1, 2, 3];
var index = arr.indexOf(1);
if (index > -1) {
array.splice(index, 1);
}
var arr = [1, 2, 3, 4];
console.log(arr.pop());
var index = arr.indexOf(2);
if (index > -1) {
arr.splice(index, 1);
}
console.log(arr)
forEach automatically extracts the elements one by one and gives them to you
It starts from the beginning of the array, and does them all.
It doesn't delete elements from the array.
a = [1, 3, 4, 6];
a.forEach(item => console.log(item));
// output is in forwards order
// and 'a' retains original contents
pop() extracts and deletes one element for you
It starts from the end of the array, and does only one.
It deletes the element from the array.
a = [1, 3, 4, 6];
while (a.length > 0) {
console.log(a.pop())
}
// items come out in reverse order
// and 'a' is being emptied so it is [] at the end
Choose your method
Do you want the last element actually removed from the array? This is what you would want if you were implementing a stack, for example. In that case, use ".pop()".
This gets one element from the end of the array and deletes it from the array.
Or do you want to just look at each element in turn from the array (starting at the beginning), without changing the array itself. This is a commoner situation. In this case, use ".forEach"

.map returns length of the resulting arrays for each iteration?

var king = [1,2,3,4];
var kong = [55,77];
var thor = king.map(function(num) { return num + 1 });
var pan = king.map(function(num) { return kong.push(num) });
console.log(kong); // [55, 77, 1, 2, 3, 4]
console.log(thor); // [2, 3, 4, 5]
console.log(pan); // [3, 4, 5, 6] ??
I thought I understood what .map was doing, but after playing around with it, I found a result that confused me. For the result of console.log(pan), I was expecting:
[[55, 77, 1], [55, 77, 1, 2], [55, 77, 1, 2, 3], [55, 77, 1, 2, 3, 4]]
However, the result is:
[3, 4, 5, 6]
It looks like it's returning the length of each resulting array? Confused.
From the MDN:
The push() method adds one or more elements to the end of an array and returns the new length of the array.
You have an array of lengths.
Here's an implementation of what you seem to want (not changing kong because it always feels better to be functional):
var pan = king.reduce(function(arr, num) {
arr.push((arr[arr.length-1]||kong).concat(num));
return arr
}, []);
You can use concat() instead.
var king = [1,2,3,4];
var kong = [55,77];
var pan = king.map(function(num) { return kong = kong.concat(num) });
console.log(pan);
push returns array length. So you have array of lengths.
You can achieve what you expect by:
var pan = king.map(function(num) {
kong.push(num);
return kong.slice(); // create array copy!
});
And do not forget to copy array, otherwise you will get an array with same array as elements.
Solution that is non destructive to kong
var king = [1, 2, 3, 4];
var kong = [55, 77];
var pan = king.map(function(_, i) {
return kong.concat(king.slice(0, i + 1));
});
console.log(pan);
map applys the function you specify to each of the elements in the array. So the answers it is giving you are correct for the first array
You don't need to manually push the elements inside a map. The map operation applies your function on every element of the array and returns a new array based on results.
To be honest that's the whole purpose of the map method.

lodash searchIndex on reverse sorted list

I have a sorted array as follows:
var array = [ 10, 10, 10, 8, 7, 6, 6, 6, 6 ];
I want to find the insertion index of 11. Given that this array is sorted in descending order, the insertion index should be 0.
Is there a way to compute this using lodash, without having to reverse() and sort() again?
Use the iteratee argument of sortedIndex() to negate the item:
_.sortedIndex(array, 11, function(item) { return -item; });
// → 0

JavaScript Array Index Insertion when out of index

How could I insert an array of items into an existing array if the start index is outside the bounds of the array I'm inserting.
For example:
[ 1, 2, 3 ]
I need to insert at index 10. I tried something like this:
Array.prototype.splice.apply(curData, [newData[0].index, 0].concat(newData));
but it respected the array bounds. This COULD be accomplished with a for loop but i'd say it wouldn't be very performant at all. Any ideas?
arrOne = [1, 2, 3];
arrTwo = [10, 11, 12, 13];
arrOne[9] = undefined;
arrOne.concat(arrTwo);

Pick random and remove from collection using underscore

I've got a collection of 20 results (objects), and what I'd like to do when a button is clicked is to:
a) Pick a random object from this collection/array
b) When the button is pressed again - I don't want that object re-picked until the collection is exhausted (i.e. until the 20 items are shown)
I thought of just splicing out the index of that collection, but I'm hoping for a cleaner way using Underscore.js
EXAMPLE:
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11...]
var getRand = _.random(0, data.length);
==> 3
Next time I press the button, I don't want the result "3" to re-appear as it's been used
I hope this makes sense
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
// cache indexes
var cache = _.map(new Array(data.length + 1).join(), function (item, index) {
return index;
});
// get random from cached array
var rand = _.random(0, cache.length);
// remove random index from cache
cache.splice(rand, 1);
console.log(rand, cache)
var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var picked = [];
$("#link").click(function() {
if(data.length == 0) return;
var pick = data.splice(_.random(0,data.length),1);
picked.push(pick);
$("#pick").html(pick);
$("#data").html(data.join(","));
$("#picked").html(picked.join(","));
});
http://jsfiddle.net/Z3vjk/
You could make an array to store the values you've used and check all new random numbers to see if they appear. This would get messy near the end of the array though as the random number generator tries to guess a single number.
If it were me I would just what you alluded to and take the elements out as you use them and place them into a temporary array. Once all elements are used, reassign the temp array to the original variable name.

Categories

Resources