Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I need to create a function that checks all numbers in an array and print them out.
My idea was something similar to this:
var array = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99];
var string = "";
var len = array.length;
After declaring the variables, i start to loop them:
for (var i = 0; i < len; i ++) {
for (var j = 0; j < len; j ++) {
//console.log(array[i], array[j]);
}
}
Console prints me value in this order:
3 3
3 6
3 67
. .
6 3
6 6
6 67
. .
I thought to create a if statement checking if array[i] is equal to array[j] then pushing the content in a new string.
You need to iterate in the outer loop until the element before the last item and in the inner loop start from the actual index plus one, to prevent to check the same element.
If duplicate is found, push the value to the duplicates array.
var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
len = array.length,
i, j,
duplicates = [];
for (i = 0; i < len - 1; i++) {
for (j = i + 1; j < len; j++) {
if (array[i] === array[j]) duplicates.push(array[i]);
}
}
console.log(duplicates);
A shorter approach by using a Set
var array = [15, 22, 88, 65, 79, 19, 93, 15, 90, 38, 77, 10, 22, 90, 99],
found = new Set,
duplicates = array.filter(v => found.has(v) || !found.add(v));
console.log(duplicates);
You can also use Set with Array.filter and Array.indexOf:
let data = [15,22,88,65,79,19,93,15,90,38,77,10,22,90,99]
let r = new Set(data.filter((v, i, a) => a.indexOf(v) !== i))
console.log(Array.from(r))
The idea is to filter the items to those who have multiple indexes found and then add them to the Set. Since Set stores unique items only it will take care of the duplicates and you get the final result.
We take advantage of the fact that Array.filter provides 3 arguments to the iteratee function - value (v), current index (i) and the actual array (a).
Related
I built a program that check if there are two common numbers in two different arrays, and then log those numbers. I was able to do that using a simple for loop that goes trough each element of the first array and check if there is an equal element in the second array. Each of the same element in the arrays are stored in a third array called "commonNumbers" which I logged at the end of the program.
const firstNumbers = [12, 45, 6, 78]
const secondNumbers = [6, 7, 12, 45]
let commonNumbers = []
for (let i = 0; i < firstNumbers.length; i++) {
for (let j = 0; j < secondNumbers.length; j++) {
if (firstNumbers[i] === secondNumbers[j]) {
commonNumbers += secondNumbers[j]
}
} }
console.log(commonNumbers)
The result for this example is the seguent:
12456
[Finished in 0.2s]
My question is about the result. I can see that the program actually worked and logged the same element in the arrays (12, 45, 6), but I can't figure out why "commonNumbers" stored the result in such a way that there are no spaces between the numbers.
I would like to clearly see each number.
For example if I call the first element of "commonNumbers" (of index 0):
commonNumbers[0] the result I will get is not going to be "12" as expected, but "1".
Same thing happen if I say: commonNumbers[2] the result is going to be "4", not "6".
Apparently "commonNumbers" array stored the element in a different way I was expecting. How can I solve this, using this "storing" method?
This is because +=, on your array, implicitly convert it to a string, as you can see in the example below, where a Number is summed to an Array.
console.log(typeof([] + 1));
Just use the comfortable .push (read more about push here) method of arrays in order to add the element:
const firstNumbers = [12, 45, 6, 78]
const secondNumbers = [6, 7, 12, 45]
let commonNumbers = []
for (let i = 0; i < firstNumbers.length; i++) {
for (let j = 0; j < secondNumbers.length; j++) {
if (firstNumbers[i] === secondNumbers[j]) {
commonNumbers.push(secondNumbers[j]);
}
} }
console.log(commonNumbers)
As a (final) side note, there are several other ways to accomplish your task, the cleverest you can probably go with is filter. You may also would take care of eventual duplicates, since if your input array has two identical numbers the commonsNumber result will contain both, which might be unintended.
The "definitive" clever solution that tries to also take care of duplicates and to loop the shorter array would be something like this:
// Inputs with duplicates, and longer array on second case.
const firstNumbers = [12, 45, 6, 78, 12, 12, 6, 45];
const secondNumbers = [6, 7, 12, 45, 45, 45, 12, 6, 99, 19, 5912, 9419, 1, 4, 8, 6, 52, 45];
// Performance: look for duplicates starting from the shortest array. Also, make a set to remove duplicate items.
const [shortestArray, longestArray] = firstNumbers.length < secondNumbers.length ? [firstNumbers, secondNumbers] : [secondNumbers, firstNumbers];
// Remove duplicates.
const dedupes = [...new Set(shortestArray)];
// Find commomn items using filter.
const commons = dedupes.filter(i => longestArray.indexOf(i) > -1);
console.log('commons is', commons);
Don't get me wrong, the solution is fine, just wanted to add "something" to the boilerplate, to take care of eventual additional scenarios.
const firstNumbers = [12, 45, 6, 78]
const secondNumbers = [6, 7, 12, 45]
let commonNumbers = []
for (let i = 0; i < firstNumbers.length; i++) {
for (let j = 0; j < secondNumbers.length; j++) {
if (firstNumbers[i] === secondNumbers[j]) {
commonNumbers.push(secondNumbers[j])
}
} }
The push method appends values to an array.
You seem to be looking for array.prototype.push (mdn). E.g.:
const firstNumbers = [12, 45, 6, 78]
const secondNumbers = [6, 7, 12, 45]
let commonNumbers = []
for (let i = 0; i < firstNumbers.length; i++)
for (let j = 0; j < secondNumbers.length; j++)
if (firstNumbers[i] === secondNumbers[j])
commonNumbers.push(secondNumbers[j]);
console.log(commonNumbers); // as an array
console.log(commonNumbers.join(', '));
why "commonNumbers" stored the result in such a way that there are no spaces between the numbers.
The + operator will try to cast its operands to compatible types. In this case, that is a string, where empty arrays [] are cast to empty strings '', and numbers 3 are cast to the corresponding string '3'. E.g. [] + 3 is the string '3'.
console.log([], typeof []);
console.log(3, typeof 3);
console.log([] + 3, typeof ([] + 3));
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to sum (ie. 4+15+10 etc... = total) the below array. I believe I'm using the right code but it doesn't seem to be working. Can someone take a look at it for me?
function beginhere() {
var arr = [4,15,10,7,6,18,1,18,8,45,55,16,9,19,11,13,14];
var total =0
var i =0
for(i < arr.length; i++) {
total += arr[i][1];
}
document.getElementById("thismessage").innerHTML = i;
}
You need just the element, without another index, because you have an array with single values and not an array of arrays.
total += arr[i];
// ^^^
and the right start value for the for statement
for (i = 0; i < arr.length; i++) {
// ^^^^^
and you need to assign the total instead of the loop variable i.
document.getElementById("thismessage").innerHTML = total;
// ^^^^^
function beginhere() {
var arr = [4, 15, 10, 7, 6, 18, 1, 18, 8, 45, 55, 16, 9, 19, 11, 13, 14],
total = 0,
i;
for (i = 0; i < arr.length; i++) {
total += arr[i];
}
document.getElementById("thismessage").innerHTML = total;
}
beginhere();
<div id="thismessage"></id>
For loop syntax was wrong.its a for(i=0; i<length; i++)
Second problem was addition with array arguments. total += arr[i];
last one the you are not print the total value.you just print the increment .but the not use because is outside loop
function beginhere() {
var arr = [4,15,10,7,6,18,1,18,8,45,55,16,9,19,11,13,14];
var total =0
var i =0
for(i=0; i < arr.length; i++) {
total += arr[i];
}
console.log(total);
}
beginhere();
Another method Array#reduce Arrow function simply use like this
var arr = [4,15,10,7,6,18,1,18,8,45,55,16,9,19,11,13,14];
var res = arr.reduce((a,b) => a+b ,0)
console.log(res)
A few corrections:
You are missing a semicolon at the beginning of your for loop;
You don't need the extra [1] after your arr[i] access; and
You probably meant to set your content to total instead of i.
A few other suggestions:
Use textContent instead of innerHTML when you don't plan on inserting tags; and
Place var i = 0 inside of your for loop (this is common practice).
function beginhere() {
var arr = [4, 15, 10, 7, 6, 18, 1, 18, 8, 45, 55, 16, 9, 19, 11, 13, 14]
var total = 0
for (var i = 0; i < arr.length; i++) {
total += arr[i]
}
document.getElementById("thismessage").textContent = total
}
beginhere()
<p id="thismessage"></p>
This is probably an odd question since I have a solution (below), but was hoping someone could show me a more succinct or readable way to do this:
I created a loop that outputs the following array:
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91]
the gaps between numbers get progressively larger:
1-0 = 1
3-1 = 2
6-3 = 3
10-6 = 4
...
91-78 = 13
etc.
I did it by creating two variables, step keeps track of the gap size and count keeps track of the current 'position' in the gap. count counts down to zero, then increases step by one.
var output = [];
var step = 0;
var count = 0;
for (var i = 0; i < 100; i++) {
if (count == 0){
step += 1;
count = step;
output.push(i);
}
count -= 1;
}
You can try the following:
var output = [];
var total = 0;
for (var i=1; i < 100; i++) {
output.push(total);
total += i;
}
The gaps between numbers simply increase by one for each step, so a for loop should be able to track this change.
You should skip useless iterations. If you want a sequence of 100 numbers, use
var output = [];
var step = 0;
for (var i = 0; i < 100; i++) {
step += i;
output.push(step);
}
If you want the general term,
aₙ = ∑ⁿᵢ₌₀ i = n*(n+1)/2
So you can also do
var output = [];
for (var i = 0; i < 100; i++) {
output.push(i * (i+1) / 2);
}
You can save the total helper variable with this solution:
var output = [0]
for (var i = 1; i < 14; i++) {
output.push(output[i - 1] + i)
}
console.log(output) // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]
This solution takes into account that the value to add the counter value to is already present at the last position in the array.
A recursive version is also possible:
output = (function f(x) {
return x.length == 14 ? x : f(x.concat([x[x.length - 1] + x.length]))
})([0])
console.log(output); // [ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91 ]
Here is no additional counter variable is needed. I use concat because it returns an array what I need for the recursive call, where push returns the new array length. The argument for concat is an array with one element with the new value to add.
Try online
If you notice the result of the for loop that is starting at index 0 and counting up isn't taking the number 23 out fo the array.
Using JavaScript Loop through evenArray removing all values that aren't even
var evenArray = [1,2,3,6,22,98,45,23,22,12];
for (var i = evenArray.length - 1; i >= 0; i--) {
if(evenArray[i] % 2 != 0){
evenArray.splice(i, 1);
}
};
console.log(evenArray);
//output to this will be 2, 6, 22, 98, 22, 12;
var evenArray = [1,2,3,6,22,98,45,23,22,12];
for (var i = 0; i < evenArray.length; i++) {
if(evenArray[i] % 2 != 0){
evenArray.splice(i, 1);
}
};
console.log(evenArray);
//output is [2, 6, 22, 98, 23, 22, 12];
When you splice a number out of the array, all of the values after that point in the array get shifted to the left.
In the second approach, at index 6 the value is 45. You detect it as odd, so you splice. Now the 23, 22, and 12 get shifted over so that 23 is now at index 6. But since you are iterating forward, your i++ moves you up to index 7, effectively skipping the 23, which is why 23 is in the result.
When you iterate backwards, you avoid this problem because all of the numbers being shifted have already been acted on.
Dylan's answer is correct explaining why one works and the other fails.
Regardless, a simple solution that will work is:
var evenArray = [1,2,3,6,22,98,45,23,22,12];
evenArray = evenArray.filter(function(val) { return val % 2 == 0; });
console.log(evenArray);
Just adding one single print into the code:
var evenArray = [1,2,3,6,22,98,45,23,22,12];
for (var i = 0; i < evenArray.length; i++) {
console.log("index:"+i+" value:"+evenArray[i])
if(evenArray[i] % 2 != 0){
evenArray.splice(i, 1);
}
}
The output like this:
index:0 value:1
index:1 value:3
index:2 value:22
index:3 value:98
index:4 value:45
index:5 value:22
index:6 value:12
Compare to the origin array, it's cutting.
The reason is splice is cutting your array dynamically, so the index is changed after splice, value 23 origin index is 7, but after the splice it move to before index 6
[1,2,3,6,22,98,45,23,22,12];
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have an array arr[0,1,2,3,..10] in Java script.I need to make a new array with first element of new array=sum of all elements except the first element of the previous array,and goes on.
Description: I have
Array=new Arr[0,1,2,3,..10].
I need an
Array=new new Array[first element,second element..]
where
first element=(1+2+..10)-0 ,
second element=(0+2+3+..10)-1,
third element=(0+1+3+..10)-2,
.. goes on till last element.
var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = myArray.reduce(function(previous, current) {
return previous + current;
}, 0);
var newArray = myArray.map(function(currentElement) {
return sum - currentElement;
});
console.log(newArray);
Output
[ 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45 ]
Algorithm goes like this
Just calculate the sum of all elements in the array
Traverse the array and reduce the element value from the sum and push into new array
Code
var sum = 0;
var result = [];
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
for (var i = 0; i < arr.length; i++) {
result.push(sum - arr[i]);
}
console.log(result);
Note that, this can be done with short snippets of code as well using a combination of Array.reduce and Array.every, Array.slice. But these all methods have browser compatibility issues as they are not supported in older IE browsers.
It looks like you'll have to do something like this:
var nums = new Array(0,1,2,3,4,5,6,7,8,9,10);
var sum = Function('return ' + nums.join('+') + ';')();
var final = [];
for(j = 0; j < nums.length; j++){
final.push(sum - (2 * nums[j]) );
}
console.log(final);
The reason you have to do (2 * nums[i]) in the last step is:
To get rid of the item from the original addition (the 2 in the line below - from your code),
To subtract it at the end of the line.
var third element=(0+1+3+..10)-2,
fiddle
- Cred to #wared for the sum function -
You can do this:
arr = [0,1,2,3,4,5,6,7,8,9,10]
//Sum them all
sum = 0
for(i=0; i<arr.length; i++){
sum+=arr[i];
}
//Calculate the result
result = []
for(i=0; i<arr.length; i++){
result.push(sum-arr[i]);
}
alert(result);
Check this fiddle: http://jsfiddle.net/eg7F6/
This is the generic approach:
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = array.reduce(function (sum, value) { return sum+= value });
var newArray = array.map(function(value) { return sum - value });
However, if the array has always values from 0 to 10, you could do some shortcut – but at this point, I do not understand the point of having that.