let array = [1, 2, 3];
function lastElement(array)
{
if (array === [])
{
return null;
}
else
{
return array.slice(-1);
}
}
you are doing it in the wrong way, you cannot check if an array is empty like you did.
function lastElement(array) {
if(array.length == 0) return null
return array[array.length - 1]
}
array.length returns the count of elements inside an array.
You also need not to add an else statement because if we are returning from a functions, the code below that line does not get executed.
Hi I seen you are facing the issue of checking array and slice the data also.
Simply if you want to check the array is empty or not you will using something like this in the js
To get the last element of an array you can use
let array = [1, 2, 3];
console.log(array.length-1);
To Check array is empty and also get the last element of an array
let array = [1, 2, 3];
function lastElement(array) {
if(array.length == 0) return null
return array[array.length - 1]
}
console.log(lastElement(array))
To know more about slice which you have used in the above problem click here
Related
I'm making some practice with Javascript. This exercise from js.checkio.org asks this:
Not all of the elements are important. What you need to do here is to remove from the array all of the elements before the given one. We have two edge cases here: (1) if a cutting element cannot be found, then the array shouldn't be changed. (2) if the array is empty, then it should remain empty.
Here is my code:
function removeAllBefore(array, number) {
if (array.length === 0)
return array;
for (let element of array)
if (element === number)
filtered = array.filter(n => n => number);
return filtered;
}
console.log(removeAllBefore([1, 2, 3, 4, 5], 2));
I am able to have the new array's values, the problem is with the statement where "if (element !== number) return array", I can't put it in the code without errors and now I am stuck and curious about the solution.
Thanks for all the support
Carlo
(2) is a bit misleading as special case, as an empty array won't contain the element, and thus returning it unchanged as (1) requires is already what (2) asks for.
Otherwise learn about indexOf() and slice() for example:
function removeAllBefore(array, number) {
var position = array.indexOf(number);
if(position === -1) // not found
return array;
return array.slice(position);
}
console.log(JSON.stringify(removeAllBefore([1, 2, 3, 4, 5], 2))); // original test
console.log(JSON.stringify(removeAllBefore([1, 3, 4, 5], 2))); // "unchanged" test
console.log(JSON.stringify(removeAllBefore([], 2))); // empty test
(JSON.stringify() is added only to show the arrays in one line - they would be printed in a one-element-per-line format otherwise)
function removeAllBefore (array, number) {
const indexOfElement = array.indexOf(number);
if(indexOfElement !== -1) {
return array.splice(indexOfElement, array.length - 1);
}
return array;
}
console.log(removeAllBefore([1, 2, 3, 4, 5], 6)); // element not found
console.log(removeAllBefore([1, 2, 3, 4, 5], 3)); // found element
console.log(removeAllBefore([], 6)); // empty array
First find the index of the element, then just use .splice() to remove elements before this index.
function removeAllBefore(array, number) {
let filtered = [];
if (array.length === 0) return array;
for (let element of array)
if (element === number)
array.splice(0, array.indexOf(element))
filtered = array
return filtered;
}
console.log(removeAllBefore([1, 2, 3, 4, 5], 2));
This removes all values preceding the one you have defined, and leaves the rest including the one you have defined
The splice function takes 2 arguments, the index you are removing from and the index before the last element to remove: splice(//from beginning of array, //to index before last element to remove) ...
And the indexOf function gets the index of the value you have defined
I'm trying to remove an item from an array using the indexOf() with splice() technique suggested. This is what's happening
let someArray: string[] = [first, second, third, fourth, fifth, sixth];
let newArray: string[] = someArray.splice(3, 1);
console.log(newArray);
//deisred result = [first, second, third, fifth, sixth]
//result I'm getting = [fourth]
That's not what virtually every article I've come across says should happen. Can someone shed light on this?
UPDATE
I discovered this problem in my code when I was only ghetting 1 result where I was expecting more and tracked it back to this point.
Because when you splice an array you are mutating it, which means you are changing the original array. You're storing the result (the element you're splicing from the array) within the "newArray" variable that you have created here. So this:
var arr = [1, 2, 3, 4];
var mine = arr.splice(1, 1);
console.log(mine);
console.log(arr);
would return the original ray minus index one if we print arr to the console, and will return [2] if we print mine to the console. To get the output you're expecting, you would have to perform a different operation such as iterating through the array and utilizing splice differently. Here is an example:
var arr = [1, 2, 3, 4];
var mine = [];
for(var i = 0; i < arr.length; i++) {
if(i !== 3) {
mine.push(arr[i]);
}
}
Now I am not mutating the original array, and I am simply pushing the elements to a new array.
But if you want to simply mutate the original array and not store the new array in some sort of variable you can simply splice the original array:
var arr = [1, 2, 3, 4];
arr.splice(3, 1);
console.log(arr);
However, if you are passing it to a function, i'd probably not mutate an array outside of the function, and i'd simply return a value and store that value in a new variable:
var arr = [1, 2, 3, 4];
function deleteIndex(ar, i) {
var a = [];
ar.forEach(function(elt, index) {
if(index === i) {
}
else {
a.push(elt);
}
});
return a;
}
var newArr = deleteIndex(arr, 3);
console.log(newArr);
This way you can delete any index, or pass a function and criteria that you would want to use to determine if an index should be deleted, without changing to top-level structure of your original array by utilizing functional programming. There are also some function in the underscore module that can help you if that's the case.
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;
}
I am currently working on a small home project, and I am trying to push an array into an array of arrays, if said array does not already exist in the array of arrays.
var arrayArr = [[1,4]];
function pushArr() {
var tempArr = [1, 3];
var tempArr2 = [1, 4];
for(i = 0; i < arrayArr.length, i++)
if(!arrayArr.indexOf(tempArr[i])) {
arrayArr.push(tempArr[i]);
} else {
//other logic
}
}
Now, I know this example does not really make sense in the real world, it's just to illustrate my concern. How do I search through an array of arrays to make sure, that I don't create duplicates.
If you have any questions, please ask.
Thanks !
In my solution, in isArrayInArray(), I'm looping through each element in the main array arrayArr. I'm then comparing if the first and second element of each given array match. If so, the array has been added already so it'll return true.
var arrayArr = [[1, 4]];
pushArray([1, 4]); // does not get added
pushArray([1, 3]); // gets added
console.log(arrayArr);
function isArrayInArray(arrayToSearch, arrayToFind) {
for (let i = 0; i < arrayToSearch.length; i++) {
if (arrayToSearch[i][0] === arrayToFind[0] && arrayToSearch[i][1] === arrayToFind[1]) {
return true;
}
}
return false;
}
function pushArray(array) {
if (!isArrayInArray(arrayArr, array)) {
arrayArr.push(array);
}
}
You know [1,2] === [1,2] is false.
Please refer to How to Compare two Arrays are Equal using Javascript?
Even if you have the following:
let a = [1,2];
let b = [1,2];
Both a and b hold two different references to to arrays that have the same numbers. They are not equal !
let a = [1,2];
let b = [1,2];
console.log(a === b);
If we by pass this and we assume that for our problem that two arrays with the same length and the same data are the same, we can try to call the function arrayCanBePushed, before we want to append an array to our array of arrays and if it returns true, then we can proceed with the push.
var arrayOfArrays = [[1,2],[2,3],[3,4,5],[7]];
function arrayCanBePushed(arr){
return !arrayOfArrays.filter(a => a.length === arr.length)
.some(a => a.every(ele=>arr.includes(ele)));
}
console.log(arrayCanBePushed([1,2]));
console.log(arrayCanBePushed([1,2,3]));
Tried to keep the answer as simple as possible. Basically we are iterating over arrayArr and checking if all of the elements of the input array match all of the elements of any of the element arrays. So it should be simply an every nested in a some. However if we are comparing just two-element arrays (array to string conversion should be pretty fast) as you have now clarified in your answer then I would use string comparison as illustrated in pushArr1. This is the general direction you were heading in your first attempt so I added it to my answer.
var arrayArr = [[1, 3, 5]];
var tempArr = [1, 3, 5];
var tempArr2 = [1, 4];
pushArr1(tempArr);
function pushArr(temp)
{
if(!arrayArr.some(function(e){
return e.every(function(e1, i)
{
return e1 === temp[i];
})
})) arrayArr.push(temp);
console.log(arrayArr);
}
function pushArr1(temp)
{
if(!arrayArr.some(function(e){return e.join(",") === temp.join(",")})) arrayArr.push(temp);
console.log(arrayArr);
}
I was trying to solve an algorithm challenge which required;
Drop the elements of an array (first argument), starting from the
front, until the predicate (second argument) returns true.
The second argument, func, is a function you'll use to test the first
elements of the array to decide if you should drop it or not.
Return the rest of the array, otherwise return an empty array.
Though I have been able to come up with a lengthy solution to this through looping the array I was wondering if there is a way to implement the break statement inside the methods.
Could it be accomplish by redefining the Array.prototype.filter method to accept a break statement ?
Though the solution could have been easy as such the methods of arrays in JavaScript doesn't accept this. How do you bypass that?
function dropElements(arr, func) {
return arr.filter(func);
}
You can just use for loop and when function returns true you can just break loop and return results from that index.
var arr = [1, 2, 3, 4, 5, 6, 7, 8];
function drop(data, func) {
var result = [];
for (var i = 0; i < data.length; i++) {
var check = func(data[i]);
if (check) {
result = data.slice(i);
break;
}
}
return result;
}
var result = drop(arr, e => e == 4)
console.log(result)
You can also use findIndex() and if match is found you can slice array from that index otherwise return empty array.
var arr = [1, 2, 3 ,4 ,5 ,6 ,7, 8];
var index = arr.findIndex(e => e == 4)
var result = index != -1 ? arr.slice(index) : []
console.log(result)