Copy first element in an array and replace the last - javascript

I have a javascript array with x amount of values.
How can I replace the last element in that array with the first? (Not switch positions but remove the last array and put the first in the last position)
Example:
Initial Array: [9, 14, 23 ,12 ,1]
Final Array: [9, 14, 23, 12, 9]

array[array.length-1] = array[0];
You don't need to know very much. For starters see JavaScript Array Object.

You can use any values for the array! Hope this helps! :)
// replaces the last index of an array with the first.
var replace = function(InputArray){
//saves the first index of the array in var a
var a = InputArray[0];
//removes the last index of the array
InputArray.pop;
//places a copy of the first index in the place where the last index was
InputArray.push(a);
//returns the array
return InputArray;
}
//call the function
replace([9, 14, 23 ,12 ,1]);
// result => [9, 14, 23, 12, 1, 9]
//If you want, you can log it in the console!
console.log(replace([9, 14, 23 ,12 ,1]));

Related

JS cannot call function on array items

I created a function to check an array if the element of the array is divisible by the next item. If not is shall remove the next item from the array.
I created a test array consisting of two arrays. When I loop over them and console.log them they get returned as expected.
When I call my function (deleteItem) in the for loop instead of the console.log it just returns the result of the first array element and not the second. I am really confused and do not understand this. Can anyone please give me a hint what I am doing wrong?
Thank you in advance!
let testArray = [[240,12, 10, 8,23],[240,12, 10, 8,24]];
function deleteItem(array) {
if(array.length<=1){
return array;
}
else{
for(i=0; i<array.length-1;i++) {
let changed = true;
while(changed){
if(array[i]%array[i+1]!=0) {
array.splice(i+1,1);
i=0;
break;
}
else {changed=false};
}
}
}
return array;
}
If I only console log it returns both elements as expected:
for(i=0;i<testArray.length;i++){
console.log( testArray[i]);
//console.log(deleteItem( testArray[i]));
}
returns:
[240, 12, 10, 8, 23]
[240, 12, 10, 8, 24]
If I use my function it only calls the first array element
for(i=0;i<testArray.length;i++){
console.log( testArray[i]);
console.log(deleteItem( testArray[i]));
}
returns:
[240, 12, 10, 8, 23]
[240, 12]
I expect:
[240, 12, 10, 8, 23]
[240, 12]
[240, 12, 10, 8, 24]
[240, 12]
Don't forget to declare your for-loop variable with a "let".
It works fine as soon as you add the let. (Same inside the deleteItem function)
for(let i = 0; i < testArray.length; i++){
console.log(testArray[i]);
console.log(deleteItem(testArray[i]));
}
There is no problem when you just loop through your testArray and output every element but inside your deleteItem() function, you have another for-loop with a variable named "i" that is not declared locally.
That means:
You start the testArray loop with a global i = 0. Then you call the deleteItem function that also uses the same global i for its for-loop. So after the deleteItem function is done, the global i is set to 4 and the original for-loop condition doesn't hold anymore. That's why the deleteItem function is not called for your second testArray element.

Stand in Line Freecodecamp

Im currently working thru the exercises on the javascript portion of the freecodecamp site and Im trying to understand why a particular method worked in solving it.
function nextInLine(arr, item) {
// Your code here
arr.push(item);
var firstItem = arr.shift(arr);
return firstItem; // Change this line
}
Im trying to understand why I had to create the variable firstItem in the first place? Is there another way I could of went about solving this exercise? If so please let me know how you went about solving it.
Welcome to Stack Overflow :)
I've also gone through this task as part of undertaking the Free Code Camp front end certification. For reference, this is the task: https://www.freecodecamp.com/challenges/stand-in-line
Write a function nextInLine which takes an array (arr) and a number
(item) as arguments. Add the number to the end of the array, then
remove the first element of array. The nextInLine function should then
return the element that was removed.
While your solution delivers the desired outcome, it is possible to solve this task without declaring a variable (firstItem in your code). I've prepared and demo with description for you here: http://codepen.io/PiotrBerebecki/pen/xEYbgv
The crucial thing is to understand that:
The shift() method removes the first element from an array AND returns
that element. This method changes the length of the array.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
function nextInLine(arr, item) {
// arr is now: [5,6,7,8,9]
arr.push(item); // add 10 to the and of array
// arr is now: [5,6,7,8,9,10]
return arr.shift(); // remove first element of arr (5)
// and then return this first element (5),
// arr is now [6,7,8,9,10]
}
var testArr = [5,6,7,8,9];
console.log(nextInLine(testArr, 10)); // 5
console.log("After: " + JSON.stringify(testArr)); // After: [6,7,8,9,10]
The .shift function doesn't use any arguments. It just removes the first element of array one by one.
Here is the correct code.
function nextInLine(arr, item) {
arr.push(item);
var remove=arr.shift();
}
return arr.shift(arr);
with out declaring the variable to return
function nextInLine(arr, item){
arr.push(item); //this will add new element to the array, for our case, our array become [10, 11, 12, 13, 14, 15]
return arr.shift(arr); //the shift() method will remove the first //element and then return its value.
//for our case, our new array becomes [11, 12, 13, 14 ,15], 10 will be returned as the value of the removed element
return item; //will return the value of the item argument
};
const myArray = [10, 11, 12, 13, 14];
console.log(nextInLine(myArray, 15));
//array.push(item) in this case will add 15 to the end of the array, and the new array will now be [10, 11, 12, 13, 14, 15]
console.log(myArray);
//arr.shift(arr) will take the new array[10, 11, 12, 13, 14, 15] and remove the first element, which is "10", and then return it. Our new array will now be [11, 12, 13, 14, 15].

Reducing array of items into a single array list [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 6 years ago.
Below is my array if items that I want to reduce it to a single list of arrays..
var input=[
[
2
],
[
3,
13
],
[
4,
14
],
[
5,
15,
25,
35
]
]
var output=[
2,
3,
13,
4,
14,
5,
15,
25,
35
]
My code:
function reduceArray(item){
for(var i=0;i<item.length;i++){
return i;
}
}
var result=result.map((item)=>{
if(item.length>0){
return reduceArray(item);
}else{
return item;
}
})
which produces the same result.Can anyone please figure out where I'm doing wrong or any other approach to achieve this..Thanks
input.reduce(function(a, x) { return a.concat(x); });
// => [2, 3, 13, 4, 14, 5, 15, 25, 35]
reduce sets the accumulator to the first element (or a starting value if provided), then calls the function with the accumulator and each successive element. The function we provide is concatenation. If we say input is [a, b, c], then the above command will be equivalent to a.concat(b).concat(c). [concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) produces a new array by smushing two or more arrays together.
EDIT: Actually, there is another possible answer:
Array.prototype.concat.apply(input[0], array.slice(1));
// => [2, 3, 13, 4, 14, 5, 15, 25, 35]
This directly calls concat with multiple arguments; if input is again [a, b, c], then this is equivalent to a.concat(b, c). apply calls a function with a given receiver and arguments; slice will give us just a part of the array, in this case everything starting from the first element (which we need to chop off since it needs to be the receiver of the concat call).
One liner would be
input = [[2],[3,13],[4,14],[5,15,25,35]];
[].concat.apply([],input);
You can use lodash's flattenDeep()
_.flattenDeep([1, [2, [3, [4]], 5]]);
// → [1, 2, 3, 4, 5]
User concat.check this for more information http://www.w3schools.com/jsref/jsref_concat_array.asp
var input=[[2],[3,13],[4,14],[5,15,25,35]];
var output=[];
for(var i = 0; i < input.length; i++)
{
output = output.concat(input[i]);
}
console.log(output);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
use concat is the perfect way
The concat() method is used to join two or more arrays.
This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.
var newArr = [];
for(var i = 0; i < input.length; i++)
{
newArr = newArr.concat(input[i]);
}
console.log(newArr);

how to compare the elements of one array to the index of another array in Javascript?

I'm trying to compare the elements of an array(Array1) to the positions of the other array(Array2) and generate a new array(Array3) which contains the elements of Array2 whose positions are equal to the elements of Array1.
var Array1 = [1, 2, 6] // Dynamic array, maxlength= 6
var Array2 = [6, 8, 9, 3, 5, 2] // dynamic array of length=6
var Array3 = [6, 8, 2] // note that positions are form 1-6 and not 0-5
How can I achieve this?
The solution to your problem is
Array1.map(function(key) {return Array2[key - 1];});
The use of key - 1 has to do with the fact that you are denoting the first element of Array2 as position "1".
If instead you followed the more popular programming convention that the first element of Array2 is position "0" (or index 0), then the solution would be
Array1.map(function(key) {return Array2[key];});

How come I can't use the length number from this array?

I created an array, and when I try to get the length of the array it works fine.
var map = [
[3, 0, 0, 2],
[7, 6, 6, 8],
[7, 6, 6, 8],
[5, 1, 1, 4]
];
var i = map.length;
i outputs 4.
When I try to use the i variable to get the column using var j = map[i].length; the console returns "map[i] is undefined". How come this won't work, but replacing i with an actual number works?
Here is an example jsfiddle, just uncomment line 11.
i is equal to 4, as you said. JS array indices start from 0, so the last element in your array is map[3] which means there is no element at map[4]
You need to do map[i-1] - this code should work:
var j = map[i-1].length;
And here is it working in your jsfiddle: https://jsfiddle.net/zk7f8Ls2/2/
Because table index are zero-based. The table length is 4 but indexes are 0, 1, 2 and 3. When you try to access index 4, you will get an error.
It's because i is 4, and remember that arrays start with 0 if you want to see the last item of the array just add -1 map[i-1]

Categories