Reputation: 13
I have a little code written where I am tracking indexes which I have successfully but finding difficulty removing them from the array so I do same with what I am left with.
var v = [4, 7, 2,5, 3]
var f = []
for (let i = 1; i < v.length; i += 2){
/*(point1)this line doesn't seem to work*/
if (v[i] > v[i] - 1)
/*(point 2) Instead of console.log I want to delete every of v[i] */
console.log(v[i])
Output
7
5
Expected Output when v[I] is deleted
v = [4,2,3]
Preferably I would like to do something like splice v[i] if v[i] > v[i] -1 and get back v as with the spliced elements.
I first tested point 1 with this similar logic in the command line and it worked but.....;
if ((b[1] -1) > b[0]){console.log(b[2])}
Output
3
```
Upvotes: 0
Views: 2158
Reputation: 76
Try filter method of array object.
Instead of removing element from current array you can filter out values you want and get new array by using filter method of array object.
var arr = [0, 1, 2, 3];
var filteredArr = arr.filter(function(element, currentIndex, arrObj) {
//currentIndex and arrObj can be used to form your desired condition but they are
//optional parameter
// below is the filter condition to be applied on each element
return element > 0;
});
console.log('filteredArr will have all the elements of the array which satisfies the filter condition:', filteredArr);
Upvotes: 0
Reputation: 11001
Build new array res
by eliminating the unwanted elements from array v
var v = [4, 7, 2, 5, 3];
var res = [];
res.push(v[0]);
for (let i = 1; i < v.length; i += 1) {
if (v[i - 1] > v[i]) {
res.push(v[i]);
}
}
console.log(res);
Upvotes: 1
Reputation: 313
To delete a specific index of an array you can use the splice like below.
var fruits = ["apple", "orange", "avocado", "banana"];
//remove one element starting from index 2
var removed = fruits.splice(2, 1);
//fruits is ["apple", "orange", "banana"]
//removed is ["avocado"]
However, regarding to the if logic it will be always true because you are testing if a number is greather than itself subtracted by 1. If you are trying to test if the value in current array position is greather than the value in the previous position, so you should so this.
if (v[i] > v[i-1])
Upvotes: 0