Get the next two proceeding elements from a JavaScript array - javascript

I have a javascript array
And i wish to get the next preceeding two elements using a function and slice.
I'm not getting the result. Is there any way to go around this?
var arr = [1,2,3,4,5,6,7,8,9]
function get(arr){
for(var i=0; i<arr.length; i++){
console.log(arr.slice(i, 3))
}}
// Now when I call the function
get(arr)
// Funny output
[1, 2, 3]
[2, 3]
[3]
[]
[]
[]
[]
[]
[]
[]
[]

You need the index instead of the length with Array#slice
Syntax
arr.slice([begin[, end]])
...
end Optional
Zero-based index before which to end extraction. slice extracts up to but not including end.
For example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3).
A negative index can be used, indicating an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence.
If end is omitted, slice extracts through the end of the sequence (arr.length).
If end is greater than the length of the sequence, slice extracts through to the end of the sequence (arr.length).
function get(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(arr.slice(i, i + 3));
}
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
get(arr);

The second parameter to slice() is end index. So what you're saying is give me all elements from i to index 3 (not-inclusive).
What you should be saying is slice(i, i+3)

slice(i, 3) basically means you want a new array with elements between the index before index i and index 3. You can just use a simple for loop instead to return the proceeding two elements of each element like this:
var arr = [1,2,3,4,5,6,7,8,9]
function get(x){
for (i = 0; i < x.length - 2; i++){
console.log("The proceeding two elements of " + x[i] + " is " + x[i+1] + " and " + x[i+2]);
}
}
get(arr);
N.B. The - 2 in the for loop's x.length - 2 is to prevent returning an undefined result since the last two elements won't have two proceeding elements.
Or if you prefer using slice(), you can do this:
var arr = [1,2,3,4,5,6,7,8,9]
function get(x){
for (i = 0; i < x.length - 2; i++){
console.log(x.slice(i, i+3));
}
}
get(arr);
Again, the - 2 in the for loop's x.length - 2 is to prevent returning an undefined result or an incomplete result since the last two elements won't have two proceeding elements.

Related

How can I iterate over an element in an array but not move from the index until a condition is fulfill?

Hi fam happy Valentine's.
I'm not looking for a code solution but some insights about how could I go about iterating over an array let's call it array = [1, 1, 1], and not moving to the next element in the array until a condition is fulfilled. For example I want to start at index 0 and only go to the next index (1) after the value of such index is (modified/changed) to be greater than the value of the index before it. At 0 index we have the value 1, I want before moving to index 1 to change the value of index 1 to be greater then the value of index 0. Something like this if we have array = [1, 1, 1] I want to iterate over the array, start at 0 index. Compare if the value of 0 index is greater or equal than the value of index 1 (the next index) If so than add 1 to the value of index 1 until that value is greater than the value of index 0. First iteration we get array = [1, 2, 1].
Next iteration we get array = [1, 2, 3].
At this point I have tried to iterate over the array with a for loop grab each element, compare and add 1 to the element but when I get to the last element it does not add anything since I am at the end of the array and there is no item to loop over. I get array = [1, 2, 2] Please help fam. This is what I have so far.
// array
const array = [1, 1, 1]
// iterating over array
for (let i = 0; i < array.length; i++) {
// compare
if (array[i] >= array[i + 1]) {
// increase next number by 1
array[i + 1] += 1
}
}
You could start from index 1, because you can not change the value at index 0 because of the missing previous value.
Inside the loop increment the value until it is greater than the value at the last index.
const array = [1, 1, 1]
for (let i = 1; i < array.length; i++) {
while (array[i] <= array[i - 1]) array[i]++;
}
console.log(array);
If you don't want to iterate for the increment, you could update the value directly.
const array = [1.2, 1, 1]
for (let i = 1; i < array.length; i++) {
if (array[i] <= array[i - 1]) array[i] = Math.floor(array[i - 1] + 1);
}
console.log(array);
Happy Valentines!
Let's look at what may be causing your array to return [1,2,2]. Good practice (And a bit tedious) is to follow along your inputs and see item by item how your array gets manipulated.
input: [1,1,1]
First Pass: [1,1,1], changes to [1,2,1]
Second Pass:[1,2,1] changes to [1,2,2]
You may have noticed the undesired behaviour happens on the second pass. It's because you're adding 1 to the value and not incrementing based on the index you're on.
Now.. lets get to fixing!
If we assume your input is always [1,1,1] (ASSUMPTIONS MATTER :) )
you can simply change array.
array[i + 1] += 1 to array[i+1] += array[i]
If you're looking for a more comprehensive approach where you can take any array input, sort and display an incrementing array -- that's a little further ahead! Focus on the fundamentals :)

Reverse an integer array using same array variable [duplicate]

This question already has answers here:
JS: Reverse an Array but Reverse the Original Array Only --> Error: running with no output
(6 answers)
Reversing an array in javascript?
(3 answers)
Reversing an array without 'reverse' or duplicating an array
(10 answers)
Closed 1 year ago.
I want to use the same variable array to output the reverse an integer array. But, I only got the first value print out. Not sure where I did wrong.
Here is my code:
let array = [3, 8, 9, 6, 4, 2]
reverseArray(array);
function reverseArray(array){
let left =0;
for(i = 0; i <= array.length - 1; i++){
let right = array.length - 1 - i;
let temp = right;
right = left;
left = temp;
array = array[left];
}
console.log(array);
}
Assuming this is a learning exercise, note that you are iterating too many times:
function reverseArray(array){
const len = array.length;
for (let i = 0; i < len/2; ++i) {
const temp = array[i];
const tail = len - i - 1;
array[i] = array[tail];
array[tail] = temp;
}
}
const array = [3, 8, 9, 6, 4, 2];
reverseArray(array);
console.log(array);
As others have pointed out, the reason for truncation is the fact that you assigned an array element to the array variable, turning it from an array into a scalar.
"In real life", you should use array.reverse().
it's because you set the array as a single value by doing array = array[left].
you just override the array variable and placing a single element inside it.
changing this line to array[right] = array[left] would be a good start.
if you want to fix it all, you need to iterate only through HALF of the array (so that you won't reverse it twice - back to normal), and make the whole swap (not just replace one element):
let array = [3, 8, 9, 6, 4, 2]
reverseArray(array);
function reverseArray(array){
for(i = 0; i < array.length / 2; i++){
let right = array.length - 1 - i;
let temp = array[right];
array[right] = array[i];
array[i] = temp;
}
console.log(array);
}
Note: if you want to reverse an array you can simply use the array prototype "reverse" function like this:
let array = [3, 8, 9, 6, 4, 2];
array = array.reverse();
console.log(array);
Actually you changing index so right use to store index not value and in the last line array = array[left] is you are trying to give value and that is array[0] = 1 so that's why 1 is coming
Right way to do this
let array = [3, 8, 9, 6, 4,2]
reverseArray(array);
function reverseArray(array){
for(i = 0; i <= (array.length - 1)/2; i++){// need to iterate only half otherwise it remain same so for exampale 0th index replace with 4th index and 4th with 0 so at last both at their same position
let right = array.length - 1 - i;
let temp = array[right];
array[right] = array[i];
array[i] = temp;
}
console.log(array);}
Just use build in NodeJs function:
array.reverse()
What you are actually doing wrong is
array = array[left]
On the right side of this equation is a value of array at a specific index while on the right side of this array is a whole array

JavaScript - reverse array in place

I am trying to write code that reverses an array in place without using the reverse function (I'm busy learning JS so just doing an exercise from Eloquent JavaScript).
function reverseArrayInPlace(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[(arr.length - 1) - i];
}
return arr;
}
This was the code that I wrote which doesn't quite work, I know this is because I have already reassigned arr[0] and arr[1] so if I call reverseArrayInPlace([1, 2, 3, 4 ,5]), [5, 4, 3, 4, 5] is returned.
This was given as the solution:
function reverseArrayInPlace(array) {
for (let i = 0; i < Math.floor(array.length / 2); i++) {
let old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
Could anyone please explain what's happening in the solution so I can better understand? Thanks :)
So here is what is happening in this function:
for(let i = 0; i < Math.floor(array.length / 2); i++):
they are using the Math.floor() method to make sure that you only iterate through half of the array. That is why your original solution repeated elements instead of reversing them.
let old = array[i]:
This is a temporary variable to hold the element at the current index in the loop while you swap them.
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
this swaps the elements.
which only leaves return array;
You only need to loop over half of the array since you are swapping items; if you loop over the entire array, you will swap each item twice, not changing the array at all. In each iteration, you just copy over the value at the reflected index, instead of transposing the two values, for which you need a temporary variable to store one of the values.
Say you have an array [1, 2, 3, 4, 5]. The code starts from left most element, and swap it with the right most element. so you get [5, 2, 3, 4, 1]. Then it does the same for the next element in the array, swap it with the second to right element, and you'll get [5, 4, 3, 2, 1]. Math.floor(array.length) make sure that the already swapped elements don't swap again, so it will only go through the first half of the array.

Why doesn't my selection sort code work when there are duplicate numbers?

I've tested my code with arrays that have non-duplicate values, and it seems to work fine. When I do have duplicates, it doesn't work.
This is what I have so far. I think the line of code where I find the minimum value of the sliced array is giving me problems.
function selectionSort(array) {
for (let i = 0; i < array.length; i++) {
let min = Math.min(...array.slice(i));
let indexMin = array.indexOf(min)
array.splice(indexMin, 1)
array.splice(i,0,min);
}
return array;
}
console.log(selectionSort([3, 0, -5, -5]));
With a test array of [3,0,-5,-5], in the first iteration of the loop, the min is -5 and the indexMin is 2. After I splice the array, I get [3,0,-5]. When I splice it again (to insert the value at the beginning of the array) I get [-5,3,0,-5] as expected. In the second iteration, I would expect the min to be the -5 at index 3... but when I console.log the min, it says it's the -5 at index 0. I specified that I want to find the min from (...array.slice(1)), so why is it setting min to -5 at index 0?
The problem is that when you have duplicates indexOf returns the index of the first one, which is not what you want once you are done with it after you've seen it once —– it always finds the first occurrence even when there are multiple.
indexOf() takes an optional second parameter to indicate where to start the search. You can pass in i to start at the correct spot skipping over the already sorted values.
function selectionSort(array) {
for (let i = 0; i < array.length; i++) {
let min = Math.min(...array.slice(i));
let indexMin = array.indexOf(min, i); // pass in i
[array[indexMin], array[i]] = [array[i], array[indexMin]]
}
return array;
}
console.log(selectionSort([4, 5, 4, 3, 3, 3, 1, 3, 1]))

Javascript's "splice" method strange behavior

I was trying to solve some of the programming challenges at "free code camp" website, The problem was to find the symmetric difference between multiple arrays and returning an array of the symmetric difference of the provided arrays.
for example the following arrays:
[1, 2, 5], [2, 3, 5], [3, 4, 5]
should return [ 1, 4, 5 ]
so that's what I came up with:
function sym() {
var final = [];
var current_array = [];
for (var i = 0; i < arguments.length; i++) {
current_array = arguments[i];
//ensures duplicates inside each array are removed first
current_array = current_array.filter(function (element, index) {
return current_array.indexOf(element) == index;
});
for (var j = 0, end = current_array.length; j < end; j++) {
if(final.indexOf(current_array[j]) < 0)
final.push(current_array[j]);
else
// for some reason "splice" isn't working properly..
// final.splice(final.indexOf(current_array[j], 1));
delete final[final.indexOf(current_array[j])];
}
}
var final_2 = [];
// Removing the empty slots caused by the "delete" keyword usage
for (var m = 0; m < final.length; m++) {
if(typeof final[m] !== 'undefined')
final_2.push(final[m]);
}
return final_2;
}
in the previous logic I created an array called final that is supposed to hold all of the elements that only exist once in all of the passed arrays, firstly I loop over the arguments parameter which represents here the arrays and for each array I loop over its elements and check if that element exists in the final array or not. If it exists I remove it from the final array, else I push it to the array.
The problem here is if I use the splice method as given in the code above, it behaves very strangely, for example for the following arrays
[1, 2, 3], [5, 2, 1, 4], the result should be: [3, 5, 4]
when I use this line
final.splice(final.indexOf(current_array[j], 1));
instead of
delete final[final.indexOf(current_array[j])];
and return the final array it returns this [ 4 ]
here is the array values at each iteration
round (0, 0): 1
round (0, 1): 1,2
round (0, 2): 1,2,3
round (1, 0): 1,2,3,5
round (1, 1): 1
round (1, 2):
round (1, 3): 4
once it gets to an element that exists in the array it removes all of the elements starting from this element until the end of the array.
I don't know exactly if I'm missing something, I tried to search for any similar problems but most of what I came up with was a problem of removing elements from an array that the person was looping over and hence missing with its indices .. In my case the array I'm trying to modify got nothing to do with the arrays I'm iterating through.
Also I believe splice modifies the array in place and returns the removed elements.. please correct me if I'm not getting it well.
You've misplaced a ), here's the correction:
final.splice( final.indexOf(current_array[j]), 1 );
An additional note: the algorithm adds 5 for the first array, removes it for the second, and adds it again for the third (since it isn't present in final anymore), resulting in [1,4,5].
With an odd number of arguments, the value is preserved, with an even number, it is removed.
A simpler way to get all unique values from all arrays (if that is the intent), is to count the occurrences and filter on a single occurrence:
function sym2() {
var count = {};
for ( var i in arguments ) {
console.log("Processing ", i );
for ( var k = 0; k < arguments[i].length; k ++)
count[ arguments[i][k] ] = (count[ arguments[i][k] ]||0) + 1;
}
var final = [];
for ( var i in count )
if ( count[i] == 1 )
final.push( i );
return final;
}
sym2([1, 2, 5], [2, 3, 5], [3, 4, 5]);
Note that this will return [1,4] rather than [1,4,5].

Categories