I'm learning basics of JavaScript as I'm more of a back-end guy.
I've got this bit of code that is returning NULL but don't
know why:
function sum(...args) {
let added = 0;
for (var x = 0; x <= args.length; x++) {
added += args[x];
}
return added;
}
console.log(sum(1, 2, 3)); // 6
The issue is that you loop goes up to the length of the array, so at the last iteration, it will try getting the value of args[length], which is undefined (array indices go from 0 to length - 1). This explains why the function returns NaN.
To fix this, simply make your function loop till length - 1, and not length.
function sum(...args) {
let added = 0;
for (var x = 0; x < args.length; x++) {
added += args[x];
}
return added;
}
console.log(sum(1, 2, 3)); // 6
Use the below code, I think its internally getting an array index out of bound exception
function sum(...args) {
let added = 0;
for (var x = 0; x < args.length; x++) {
added += args[x];
}
return added;
}
console.log(sum(1, 2, 3));
Related
I am trying to write a programme to move all the zeroes at the end of the array and retain and the original order of other elements.
Here is my code:-
var moveZeros = function (arr) {
// TODO: Program me
var k=0;
for (var i=0;i<=arr.length-1;i++){
var s=arr[i];
if (s===0){
arr.splice(i,1);
k++
}
}
for (var j=0;j<=k-1;j++){
arr.push(0);
}
return arr
}
But when zeros are next to each other like [1,0,0,1] it doesn't work.
I don't see why.
Can anybody tell?
And please also explain why k-1 not k I wrote k-1 by observing the output.
Please don't tell the answer to the original problem I just want to fix the problem with my code. :)
The problem is that in each loop you increase the i variable by one. Meaning, you go to the next index. But if you have 2 or more zeros in the row, and you remove the first one, you shouldn't change i to i + 1, because i already points at a new value in the array(which is zero) :)
var moveZeros = function (arr) {
// TODO: Program me
var k = 0;
for (var i = 0; i <= arr.length - 1;) {
var s = arr[i];
if (s === 0) {
arr.splice(i, 1);
k++;
} else {
i++;
}
}
for (var j = 0; j <= k - 1; j++) {
arr.push(0);
}
return arr;
};
console.log(moveZeros([1,0,0,2]));
I'm trying to understand why my solution to this problem is only partially working.
Problem:
Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
My Solution:
var removeDuplicates = function(nums) {
if (nums.length === 0) return 0;
for (let i = 1; i <= nums.length; i++){
if(nums[i] === nums[i-1]){
nums.splice(nums[i], 1);
}
}
return nums.length;
};
This is the outcome I'm getting on leetcode but I don't understand why my solution stops working and the '3s' are not removed?
Output screenshot:
When you splice an array while iterating over it, the whole array will change in-place. For example, let's say that indexes 0 and 1 are duplicates (i is 1). Then, if you remove index 1 from the array, what used to be at index 2 will now be at index 1, and what used to be at index 3 will now be at index 2, etc.
So, you need to subtract 1 from i when an element is removed, otherwise the next element will be skipped.
You also have an off-by-one-error - iterate i from 1 to i < nums.length so you don't go past the end of the array.
You also need to pass the index to remove to splice, not the value to remove.
var removeDuplicates = function(nums) {
for (let i = 1; i < nums.length; i++){
if(nums[i] === nums[i-1]){
nums.splice(i, 1);
i--;
}
}
return nums.length;
};
console.log(removeDuplicates([0, 0, 0]));
Simple version. Using functions already created
let array = new Set(nums);
let values = array.values();
return Array.from(values);
This'd also pass just fine on constant memory:
const removeDuplicates = function (nums) {
let count = 0;
nums.forEach(function (num) {
if (num !== nums[count]) {
nums[++count] = num;
}
});
return nums.length && count + 1;
};
function removeDuplicates(nums) {
let i = 0;
while(i < nums.length - 1) {
i += 1 - ((nums[i] === nums[i+1]) && nums.splice(i, 1).length)
}
return nums.length;
}
C# simple solution:
public int RemoveDuplicates(int[] nums) {
if (nums.Length == 0)
return 0;
var i = 0;
var start = 0;
var end = 0;
while (end < nums.Length)
{
if (nums[start] != nums[end])
{
nums[++i] = nums[end];
start = end;
}
end++;
}
return i + 1;
}
I need to Write a function "giveMeRandom" which accepts a number n and returns an array containing n random numbers between 0 and 10
I can't push generate array of n (arg) length.
It generates only one.
const giveMeRandom = function(n) {
let arrWithNums = [];
for(i = 0; i < n.length; i++) {
return arrWithNums.push(Math.floor(Math.random() * 10));
}
return arrWithNums;
}
console.log(giveMeRandom(4));
n is a number which does not have a length. Just use following for loop:
for (let i = 0; i < n; i++) {...}
Also remove the return statement inside of the loop.
The first problem is n.length. The number 4 has a length of one, and if i < 1 then the loop will not run at all. You just want n in this place instead.
The other problem is that you're returning a value at every repetition of the loop, which stops the function running. Only return a value once at the end to fix this problem.
Here's the full code:
function giveMeRandom(n) {
let arrWithNums = [];
for(i = 0; i < n; i++) {
arrWithNums.push(Math.floor(Math.random() * 10));
}
return arrWithNums;
}
console.log(giveMeRandom(4));
const giveMeRandom = function(n) {
let arrWithNums = [];
for (i = 0; i < n; i++) {
arrWithNums.push(Math.floor(Math.random() * 10));
}
return arrWithNums;
}
console.log(giveMeRandom(6));
I want the result to be the sum of every number, but instead, it only sums the first number with the rest. For example if the parameter were : 1,2,3,4,5
it should come out with 15 but instead, it became 3456. Where did i go wrong?
Thank u guys, i m new to this and thing were really complicated :((
function func1(sum) {
var result = '';
var i;
for (i = 1; i < arguments.length; i++) {
result += arguments[i] + sum;
}
return result;
}
Start with result being a number, not a string: var result = 0.
If you're iterating through arguments, you may as well skip the named first argument altogether.
Start iterating from 0, not 1.
function func1() {
var result = 0;
var i;
for (i = 0; i < arguments.length; i++) {
result += arguments[i];
}
return result;
}
console.log(func1(1, 2, 3, 4, 5));
This should work
function sum(value) {
let result = 0;
for(let i =0; i < value.length; i++) {
result +=value[i];
}
return result
}
let arry = [1,2,3,4,5]
console.log(sum(arry)) //15
Can someone please explain to me what I am doing wrong here...
This code is from eloquent javascript and it works fine
function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}
And this is what I wrote for the exercise but returns NaN..
function sum(numArray) {
let add = 0;
for (let a = 0; a <= numArray.length; a++) {
let addIndex = numArray[a];
add += addIndex;
}
return add;
}
Your for loop goes out of array indexes. You have to use:
a < numArray.length
Instead of:
a <= numArray.length
You simply add undefined to add, because you run the index count to long.
for (let a = 0; a <= numArray.length; a++) {
// ^ wrong, takes last index + 1
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4]));
The issue is because of this a <= numArray.length. Change it to a < numArray.length. This case a[5] that is the 6th element or the element at 5th index is undefined as the array starts from 0 index. So it will add an undefined with previously added number and hence it will be NaN
function sum(numArray) {
let add = 0;
for (let a = 0; a < numArray.length; a++) {
let Addindex = numArray[a];
add += Addindex;
}
return add;
}
console.log(sum([1, 2, 3, 4, 5]))
You're getting an out-of-bounds error. In your for loop, you can change it to:
for (let a = 0; a < numArray.length; a++) {
OR
for (let a = 0; a <= numArray.length - 1; a++) {
The latter works too, but is harder to read.
You can also write a function that has two parameters, an array and a callback function that adds the values of the array like
function forEach(array, arrayAdder){
for (var i = 0; i < array.length; i ++)
arrayAdder(array[i]) ;
}
We can now initialize both the array and the sum like
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], sum = 0;
After that we pass it into the function like this
forEach(array, function(number){
sum += number ;
});
Then print the answer
console.log(sum);