Javascript - How to delete items from an array at given indices [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strip/remove values in array at certain indices
How do I remove a set of elements from an array at given indices using Javascript.
Say I have an index array:
var indices = [0, 1, 3].
I want to remove elements from another array at these given indices. That other array happens to be:
var cars = ["Cow", "Dog", "Ferrari", "Monkey", "Ford"].
So, after deletion I want "Cow", "Dog", "Monkey" to be removed from cars array
I have tried the splice way:
for(var i = 0; i < indices.length; i++){
cars.splice(indices[i], 1);
}
But this code happens to change the indices of the cars array every time an item is spliced!

You can start from the last element:
for(var i = indices.length-1; i >= 0; i--){
cars.splice(indices[i], 1);
}

Try this
var cars = ["Cow", "Dog", "Ferrari", "Monkey", "Ford"];
console.log(cars);
cars.each(function(val, index){
// You can use jQuery inArray also.
//For Ex: if(jQuery.inArray(index, indices)){........}
if(val=="Cow" || val=="Dog" || val=="Monkey" ){
cars.splice(index, 1);
}
});
console.log(cars);
JAVASCRIPT: Then use .forEach instead of .each

You can use delete to remove elements without modifying the indices.
var a = [1, 2, 3, 4, 5];
delete a[2]; // deletes '3'
console.log(a); // prints [1, 2, undefined, 4, 5]
You can use splice() to remove elements and shift the rest to fill out the removed indices
var b = [1, 2, 3, 4, 5];
b.splice(2, 1); // deletes '3' and shifts the rest to left
console.log(b); // prints [1, 2, 4, 5]

Splice method deletes item completely, So As u said "But this code happens to change the indices of the cars object every time an item is spliced!" it will strictly remove element. You can use naming convention id as "Deleted" or any familiar naming id instead of removing (deleting) element if you want to maintain same array index
for(var i = 0; i < indices.length; i++){
cars[indices[i]] = "Deleted";
}
With this You can maintain same array index as you required.
Please can you explain why -1 ? its not what deserve, or Justify it.

Related

How to select the third and subsequent elements in the array in javascript [duplicate]

This question already has an answer here:
Get all elements in an array after a certain index in JavaScript
(1 answer)
Closed last month.
For example I have an array like [1, 2, 3, 4, 5] , and I want to select [3, 4, 5].
Is there a simple way to do that? Lots of thanks.
You can use slicing for this.
Lets say x = [1,2,3,4,5]. Just do s.slice(2).
You can just use a simple for loop and begin looping at the nth element of the array.
let array = [1, 2, 3, 4, 5]
for (let i = 2; i < array.length; i++) {
console.log(array[i])
}

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"

How to remove an item from a list without distorting the original list

This is what I'm trying to do, I have an array
var arr = [1, 2, 3, 4, 5];
then I want to create a new array each time by removing an item once i.e when i remove item at index 0 i should have [2, 3, 4, 5]and when i remove an item at index 1, I should have [1, 3, 4, 5] and so on till i get to arr.length-1 and each time i remove an item i still want my arr to be intact unchanged
using javaScript I have tried some array methods like splice, slice but all that changes the value of arr
how do i go about it with either javascript or python.
For Javascript, using ES6 array spread operator and slice method,
var new_array = [...a.slice(0, index), ...a.slice(index + 1)];
const cut = (a, i) => [...a.slice(0, i), ...a.slice(i + 1)];
let arr = [2, 2, 2, 4, 2];
console.log(cut(arr, 3));
console.log(arr);
For Python:
array = [1,2,3,4,5];
newarray = [value for counter, value in enumerate(array) if counter != 0 ]
PS each time you will use this list-comprehension, array will not be modified! so basically you will get the same output for newarray.
If you want to have newarray each time removed one element you need to create a function instead of list-comprehension (of course it's possible but will likely be less readable).
For JavaScript:
Try making a copy with slice() (slice returns a shallow copy of the array that you can manipulate without affecting the original array) and then using splice() to remove the value at your desired index:
newArray = slice(arr).splice(index, 1);

Choose if array element repeats itself twice -- Javascript [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 6 years ago.
There is a javascript array
var arr = [0, 1, 2, 2, 3, 3, 5];
I want to choose elements that repeats twice. In this case its 2 and 3. and i want attach them into a variable.
var a = 2, b = 3;
As far as i know there is no built-in function to do that job. How can i do that. Thanks.
You can use filter to get the values that occur twice.
var arr = [0, 1, 2, 2, 3, 3, 5];
var dups = arr.filter ( (v,i,a) => a.indexOf(v) < i );
console.log(dups);
In comments you stated you would only have doubles, but no values that occur more than twice. Note that the above would return a value more than once, if the latter would be the case.
This returns the values in an array, which is how you should work. To put them in separate values can be done as follows:
var [a, b, ...others] = dups;
...but you would have to know how many variables to reserve for that, and it does not make your further program any easier. JavaScript has many nice functions (methods) for arrays, so you should in fact leave them in an array.
There is no built in function to do that indeed.
You will have to loop thought the array and keeping track of the number of occurrences of the elements, while building a response array.
You could filter a sorted array.
var arr = [0, 1, 2, 2, 3, 3, 5],
repeats = arr.filter(function (a, i, aa) {
return aa[i - 1] === a;
});
console.log(repeats);
Most simple way to do this is the following:
var dups = [];
var arr = [0, 1, 2, 2, 3, 3, 5];
arr.forEach(function (v, i, a){
delete arr[i];
if (arr.indexOf(v) !== -1){
dups.push(v);
}
});
console.log(dups);
It's destructive however.

JQuery Remove array from array of arrays

So I have an array of 2-element arrays, and I'm wondering if any of you know how to remove an array given the two elements of an array.
For example, the array would contain the following elements:
[1, 3]
[2, 5]
[1, 1]
Given the two numbers 2 and 5 in that order, is there any way to remove the second array?
Search the array for a match by some method. You could try each comparing each list in the larger list to the list given to you, or create a list from the numbers given to you and pass that. Then compare item by item for each list until you match each item-for-item every one.
If you find it use that index and look into the splice method from the javascript library. For example my_lisy.splice(2,2) argument 1 refers to the index of the list, and argument two refers how many items to remove.
You can try something like this:
var arr = [[1, 3], [2, 5], [1, 1]];
var result = [];
for(var i = 0, len = arr.length; i < len; i++) {
// If the element is the one we don't wan't, skip it
if(arr[i][0] == 2 && arr[i][1] == 5) {
continue;
}
// Otherwise, add it to the result
result.push(arr[i]);
}
console.log(result); //[[1, 3], [1, 1]]
You can add or extract any logic from the loop to suit your needs

Categories

Resources