This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 4 years ago.
So im trying to remove the numbers 1,2,7,14 in the array but i dont know how to remove it. I did not find any solution that is similar to this
function mySelect(){
var prime1 = document.getElementById('input1').value;
var prime2 = document.getElementById('input2').value;
var n = prime1 * prime2;
console.log(n);
var foo = new Array(n);
console.log(foo.length);
var range = [];
for(var i=1;i<foo.length;i++){
range.push(i);
}
console.log(range);
// --------------------------------------------//
var half = Math.floor(n / 2), // Ensures a whole number <= num.
str = '1', // 1 will be a part of every solution.
i, j;
// Determine our increment value for the loop and starting point.
n % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2);
for (i; i <= half; i += j) {
n % i === 0 ? str += ',' + i : false;
}
str += ',' + n; // Always include the original number.
console.log(str);
}
After you pushed the values to the array you can use a filter function, like so:
let nonos = [ 1, 2, 7, 14 ];
range = range.filter((element) => !nonos.includes(element));
This code specifies the values you want removed inside an array and then runs a loop on your original array and checks whether the element you're on is included in your nonos array and if it is, don't include it in your original array, else do.
To remove all instances of the provided numbers from an array:
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function removeNumbers(array, ...numbers) {
numbers.forEach((number) => {
var index = array.indexOf(number);
while(index >= 0) {
array.splice(index, 1);
index = array.indexOf(number);
}
});
}
removeNumbers(array, 3, 2, 5, 7);
console.log(array);
find the index first and then apply splice method.
var array=[1,2,3,4,5,6,7,8,9,10]
console.log(array)
find the index of value you want to delete
let indexa=array.indexOf(2);
apply splice method to delete 1 value from applied index
array.splice(indexa,1);
console.log(array)
Related
This question already has answers here:
JS: Reverse an Array but Reverse the Original Array Only --> Error: running with no output
(6 answers)
Reversing an array in javascript?
(3 answers)
Reversing an array without 'reverse' or duplicating an array
(10 answers)
Closed 1 year ago.
I want to use the same variable array to output the reverse an integer array. But, I only got the first value print out. Not sure where I did wrong.
Here is my code:
let array = [3, 8, 9, 6, 4, 2]
reverseArray(array);
function reverseArray(array){
let left =0;
for(i = 0; i <= array.length - 1; i++){
let right = array.length - 1 - i;
let temp = right;
right = left;
left = temp;
array = array[left];
}
console.log(array);
}
Assuming this is a learning exercise, note that you are iterating too many times:
function reverseArray(array){
const len = array.length;
for (let i = 0; i < len/2; ++i) {
const temp = array[i];
const tail = len - i - 1;
array[i] = array[tail];
array[tail] = temp;
}
}
const array = [3, 8, 9, 6, 4, 2];
reverseArray(array);
console.log(array);
As others have pointed out, the reason for truncation is the fact that you assigned an array element to the array variable, turning it from an array into a scalar.
"In real life", you should use array.reverse().
it's because you set the array as a single value by doing array = array[left].
you just override the array variable and placing a single element inside it.
changing this line to array[right] = array[left] would be a good start.
if you want to fix it all, you need to iterate only through HALF of the array (so that you won't reverse it twice - back to normal), and make the whole swap (not just replace one element):
let array = [3, 8, 9, 6, 4, 2]
reverseArray(array);
function reverseArray(array){
for(i = 0; i < array.length / 2; i++){
let right = array.length - 1 - i;
let temp = array[right];
array[right] = array[i];
array[i] = temp;
}
console.log(array);
}
Note: if you want to reverse an array you can simply use the array prototype "reverse" function like this:
let array = [3, 8, 9, 6, 4, 2];
array = array.reverse();
console.log(array);
Actually you changing index so right use to store index not value and in the last line array = array[left] is you are trying to give value and that is array[0] = 1 so that's why 1 is coming
Right way to do this
let array = [3, 8, 9, 6, 4,2]
reverseArray(array);
function reverseArray(array){
for(i = 0; i <= (array.length - 1)/2; i++){// need to iterate only half otherwise it remain same so for exampale 0th index replace with 4th index and 4th with 0 so at last both at their same position
let right = array.length - 1 - i;
let temp = array[right];
array[right] = array[i];
array[i] = temp;
}
console.log(array);}
Just use build in NodeJs function:
array.reverse()
What you are actually doing wrong is
array = array[left]
On the right side of this equation is a value of array at a specific index while on the right side of this array is a whole array
Given a JavaScript function that takes in an array of numbers as the first and the only argument.
The function then removes one element from the array, upon removal, the sum of elements at odd indices is equal to the sum of elements at even indices. The function should count all the possible unique ways in which we can remove one element at a time to achieve balance between odd sum and even sum.
Example var arr = [2, 6, 4, 2];
Then the output should be 2 because, there are two elements 6 and 2 at indices 1 and 3 respectively that makes the combinations table.
When we remove 6 from the array
[2, 4, 2] the sum at odd indexes = sum at even indexes = 4
if we remove 2
[2, 6, 4] the sum at odd indices = sum at even indices = 6
The code below works perfectly. There might be other solutions but I want to understand this one, because I feel there is a concept I have to learn here. Can someone explain the logic of this algorithm please?
const arr = [2, 6, 4, 2];
const check = (arr = []) => {
var oddTotal = 0;
var evenTotal = 0;
var result = 0;
const arraySum = []
for (var i = 0; i < arr.length; ++i) {
if (i % 2 === 0) {
evenTotal += arr[i];
arraySum[i] = evenTotal
}
else {
oddTotal += arr[i];
arraySum[i] = oddTotal
}
}
for (var i = 0; i < arr.length; ++i) {
if (i % 2 === 0) {
if (arraySum[i]*2 - arr[i] + oddTotal === (arraySum[i - 1] || 0)*2 + evenTotal) {
result = result +1
};
} else if (arraySum[i]*2 - arr[i] + evenTotal === (arraySum[i - 1] || 0)*2 + oddTotal) {
result = result +1
}
}
return result;
};
I want to know how can I add 3 different number to the 3n, 3n+1 and 3n+2 indices. I mean for example I have following array :
var arr = [1,1,1,2,2,2,3,3,3]
and then I want add the (3n)th to 5 and then I want add (3n+1)th of an array to 2 and (3n+2) to 3,
I mean the final array I want to be like following result array:
var result = [6,3,4,7,4,5,8,5,6]
and I try to do it as following code:
// arr = [1,1,1,2,2,2,3,3,3]
let res = [];
for (let i = 0; i < arr.length; i++) {
res.push([arr[i*3] * 5,
arr[(i*3)+1] *2,
arr[(i*3)+2] *3])
}
This should do the trick:
var arr = [1,1,1,2,2,2,3,3,3],
add = [5,2,3], res=[];
// result = [6,3,4,7,4,5,8,5,6]
for (let i=0;i<arr.length;i+=add.length) add.forEach((v,j)=>res[i+j]=arr[i+j]+v);
console.log(JSON.stringify(res))
An alternative and even shorter solution (similar to #Robin's answer) would be:
var arr = [1,1,1,2,2,2,3,3,3],
add = [5,2,3], res=[];
res=arr.map((v,i)=>v+add[i%add.length]);
console.log(JSON.stringify(res))
( I noticed #Nina came up with a very similar answer ...)
You can simply use map, making use of the fact that its function argument takes the current index an optional second argument:
var arr = [1,1,1,2,2,2,3,3,3];
var result = arr.map((num, idx) => {
switch (idx % 3) {
case 0:
return num + 5;
case 1:
return num + 2;
case 2:
return num + 3;
}
});
console.log(result);
You could mapp the array directly by taking a closure over an index for the values array for adding.
var array = [1, 1, 1, 2, 2, 2, 3, 3, 3],
add = [5, 2, 3],
result = array.map((i => v => v + add[i++ % add.length])(0));
console.log(...result);
I have six integers stored in an array:
[2,3,4,5,6,7]
I would like to use each item in the array to check against a range of other integers 100 - 999 (i.e. all three-digit numbers) to find a number that has a remainder of 1 when divided by all the items in the array individually.
I'm not sure what javascript method to use for this. I'm trying a for loop:
function hasRemainder() {
let arr = [2,3,4,5,6,7];
for (i = 100; i < 999; i++) {
if (i % arr[0] == 1) {
return i;
}
}
}
but it has several problems I need to solve.
Instead of referring to a particular item e.g. arr[0], I need to find a way to loop through all the items in the array.
Currently, this function only returns one number (the loop stops at the first number with a remainder), but I need all the possible values in the given range.
If anyone could help with these two problems, I'd really appreciate it. Thanks.
You could map an array of values and then filter the array by checking every remainder value with one.
function hasRemainder() {
var array = [2, 3, 4, 5, 6, 7];
return Array
.from({ length: 900 }, (_, i) => i + 100)
.filter(a => array.every(b => a % b === 1));
}
console.log(hasRemainder())
This works also;
function hasRemainder() {
const arr = [2, 3, 4, 5, 6, 7];
const remainders = []
for (i = 100; i < 999; i++) {
const isRemainder = arr.every(numb => i % numb === 1)
if (isRemainder) {
remainders.push(i)
}
}
return remainders
}
This question already has answers here:
Finding out how many times an array element appears
(6 answers)
Closed 6 years ago.
just started learning JS and had a test about loops and wasn't successful in finding an answer to this:
I would like to see how many times the number 1 appears in the arrray.
All i was able to do is get a true answer when 1 appears in the array.
Been trying to figure this out since last Wednesday..
Thanks!
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
count = 1;
for (var i = 0; i < v.length; i++){
console.log (count == v[i])
}
If you want to count the number of times a value appears in the array, you firstly need to initialise a variable outside of the loop (if you initialise in the loop, the value will be reset on each iteration of that loop).
Secondly you need a conditional statement that you will check for, in this case if a value is equal to one. As its a loop, and more then one value in the array, we can get the current index's value like v[i] (which you correctly did). Now you need to plus one to your counter, counter++ is the same as counter = counter + 1;. Now the if statement i used below has the === this is an equals operator that also check to see if the two values are of the same type.
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
var count = 0;
for (var i = 0; i < v.length; i++){
if(v[i] === 1){
count++;
}
}
console.log (count);
You can make use of the filter method which returns the array with specified condition and then you can do a count by using the length property.
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
console.log((v.filter(x => x === 1)).length);
Close! What you need to do is initialize a count variable and then iterate over the array. At each index, you check if the element matches the number. If it does, you increment the count
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
var count = 0;
var number = 1;
for (var i = 0; i < v.length; i++){
if (v[i] == number) {
count++;
}
}
console.log(count);
you have to increase the count, you are only checking if the count equals what the current item is
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
count = 0;
for (var i = 0; i < v.length; i++){
var cur = v[i]; // < gets the current item
if (cur == 1) // < If the current item is 1
count += 1; // < Then increase the count by 1
console.log (count); // < Log what the count is
}
You can do this with a variety of techniques, but in your case, you need to actually check the array value for 1 as you loop, which you aren't doing.
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
// Don't assume that there are any occurrences of 1 in the array
count = 0;
for (var i = 0; i < v.length; i++){
// Test to see if the current array item is 1 and, if so, increment the counter
// The "long-hand" way:
//if(v[i] === 1){
// count++;
//}
// Above "if" could also be written using JavaScript's "ternary" operator as this:
count = (v[i] === 1) ? ++count : count;
}
// The report should be after the loop has completed.
console.log ("1 appears in the array " + count + " times.")
Here's another (of many) techniques, but this one removes the loop, the if test and the counter completely. It also takes arrays out of the algorithm, which, in turn, can make the code much easier to understand:
var v = [1, 3, 5, 4, 3, 0, 0, 1, 1];
// Turn array into string and (using regular expressions) remove any char that is not 1
var s = v.join("").replace(/[0, 2-9]+/g, "");
// Just check the length of the string after removing non-1 chars:
console.log ("1 appears in the array " + s.length + " times.");