Writing a javascript function which accepts a single array argument [duplicate] - javascript

This question already has answers here:
How to check if an array is empty or exists?
(23 answers)
Closed 2 years ago.
Please write a function called lastElement which accepts a single array argument. The function should return the last element of the array (without removing the element). If the array is empty, the function should return null.
lastElement([3,5,7]) //7
lastElement([1]) //1
lastElement([]) //null
** the code that I wrote **
let array = [3, 5, 7];
function lastElement (array) {
return array[array.length - 1];
}
I'm flummoxed on the last part with the function returning null if the array if empty.

You can update your code a tiny bit to check if the array is empty and then return null like this:
return array.length ? array[array.length - 1] : null;

Related

check the value of the of the loop you are on [duplicate]

This question already has answers here:
How to get value at a specific index of array In JavaScript?
(8 answers)
Closed 11 months ago.
I have a foreach loop for an array, with an index to tell me which loop i am on, and an item to tell me the value of the loop i am on. Probably an obvious answer, but I'd like to be able to get the item from the index. How might i do this?
const bar1beats = [1, 0.5, 0.5, 2]
bar1beats.forEach(foreachfunction);
function foreachfunction(item, index1){
checkitemof(index1 - 1)
}
The forEach function callback can accept three arguments - the item, the index, and the array itself.
function foreachfunction(item, index1, theArray){
if (index1 > 0) {
const previousItem = theArray[index1 - 1];
...
}
}

Javascript reference vs value - arrays [duplicate]

This question already has answers here:
Does JavaScript pass by reference? [duplicate]
(13 answers)
Closed 3 years ago.
Since arrays are passed to functions by reference, when I set the array to be equal to something else inside a function, and try to log it outside of the function again, why does the value remain the same even though I modified it in the function?
let arr = [1, 2];
console.log(arr); // Logs [1, 2]
add(arr, 3)
console.log(arr); // Logs [1, 2] again
function add(array, el)
{
array = [el];
console.log(array); // Logs [3]
}
Why does the console.log after calling add log out [1, 2] instead of [3] (which is the value of the el parameter)?
You aren't modifying the array.
You're changing the value of the array variable (from a reference to the old array to a reference to a new array).
For comparison, if you were to modify the existing array:
let arr = [1, 2];
console.log(arr);
add(arr, 3)
console.log(arr);
function add(array, el) {
array.length = 0;
array.push(el);
console.log(array);
}
You're confusing the scope of the array.
When you pass in an array to the function and set that variable equal to something else like so;
function add(array, el)
{
array = [el];
}
You're just setting the variable equal to something else and you're not modifying the array. If you want to modify the array you would do something like:
function add(array, el)
{
array[0]=el; // changing the first element to 3
}
Now you will see the array is updated with the first element to 3. This is how it works with updating the array.
If you want the array to be an entirely new array you would do something like:
arr = add(arr, 3);
function add(array, el)
{
array = [el];
return array;
}

how can i have the first 3 elements of an array of variable length in Javascript [duplicate]

This question already has answers here:
How to get first N number of elements from an array
(14 answers)
Closed 5 years ago.
i would like to get the first 3 elements of an array of variable length. i've sorted my array and i would like to get a Top 3.
here's what i've done :
var diffSplice = this.users.length - 1;
return this.users.sort(this.triDec).splice(0,diffSplice)
my "solution" work only for an array of 4 element ( -1 )
Is there a better way to use the splice method ?
Thanks for your help
You could use Array#slice for the first three items.
return this.users.sort(this.triDec).slice(0, 3);
Don't you want to use a const value for diffSplice like
var diffSplice = 3;
return this.users.sort(this.triDec).slice(0,diffSplice)
try running
let arr = [1, 2, 3, 4, 5];
console.log(arr.slice(0, 3));
refer to Array Silce
Fill out the deletecount for Splice:
var sortedArray = this.users.sort(this.triDec);
return sortedArray.splice(0, 3);
check MDN

Add non duplicates numbers into an Array [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 5 years ago.
I wrote a function in javaScript that checks if it is the first time the numbers has been seem, if so, it will be added to the the array. For some reason the first number is always repeating it, Ex:
if we pass [1,1,1,2,3,3,4,5]
it will print out [1,1,2,3,4,5] instead of [1,2,3,4,5]
Could anyone tell me what I'm missing ??
Thank you in advance.
var numbers = [1,1,1,1,1,2,3,4,4,4,5,5,6,6,6,8];
function eliminateDup(arr){
var myArr = [];
for(var i = 0;i<arr.length;i++){
if(!myArr[arr[i]]){
myArr.push(arr[i]);
}
}
return myArr;
}
console.log(eliminateDup(numbers));
This comparison doesn't make sense :
if(!myArr[arr[i]]){
It is true only if !myArr[arr[i]] can be converted to true.
You get twice 1 in the target array myArr because both arr[0] and arr[1] equals to 1 and myArr has an undefined element at the 1 index for the two first iterations at the time where the conditional statement is executed.
First iteration
i = 0
arr[0] = 1
myArr[1] = undefined
So if(!myArr[1]) is true.
You add 1.
Second iteration
i = 1
arr[1] = 1
myArr[0] = 1 // now valued but not used in the test
myArr[1] = undefined;
So if(!myArr[1]) is true.
You still add 1.
Third iteration
i = 2
arr[2] = 1
myArr[0] = 1
myArr[1] = 1
So if(!myArr[1]) is false.
nothing is added.
You should rather check whether the current value is not contained in the target array before adding it in the target array :
if(myArr.indexOf(arr[i])==-1){
myArr.push(arr[i]);
}
use this condition instead, for push
if(myArr.indexOf([arr[i])===-1)
myArr.push(arr[i]); will push to back of the array myArr (just like a stack) and thus element '1' will be at index 0.
myArr[arr[i]] checks if element at index arr[i] exists which it won't so will push another 1.
As suggested above use indexof() which will just search and give an index if the element exists.

Why doesn't Array(n).forEach loop n times? [duplicate]

This question already has answers here:
forEach on array of undefined created by Array constructor
(5 answers)
Closed 6 years ago.
Array(3) yields [ , , ], which has a length of 3.
[1, 2, 3].forEach loops 3 times, as expected.
Neither Array(3).forEach nor [ , , ].forEach loops at all, however.
Why is this? I thought I'd discovered a way of doing something n times without using for loops, and am disappointed to find it doesn't work!
forEach() executes the provided callback once for each element present
in the array in ascending order. It is not invoked for index
properties that have been deleted or are uninitialized (i.e. on sparse
arrays)
Example from MDN:
Fiddle
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element);
}
// Notice that index 2 is skipped since there is no item at
// that position in the array.
[2, 5, , 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[3] = 9
Have a look at MDN article.
.

Categories