How can I make my array into a formatted string? [duplicate] - javascript

This question already has answers here:
Easy way to turn JavaScript array into comma-separated list?
(22 answers)
Closed 3 years ago.
I am trying to format my array to a formatted string, how can I do that?
The instructions I was given are
Task 6 - find all odd numbers in a list.
Allow any number of Number arguments to be passed to the function.
If a value is passed to the function that is not a Number, ignore it
and continue processing the rest. If the list is empty (nothing passed
to the function, or all need to be ignored, return null).
Return a formatted string with all odd numbers in a list, for example:
"1, 3, 5"
<script>
var odd = [];
const oddNumbers = (...numbers) => {
var oddNum
var formatString;
var i;
if (numbers.length > 0) {
for (i = 0; i < numbers.length; i++) {
if (isNaN(numbers[i]) === false && (numbers[i] % 2 !== 0)) {
odd.push(numbers[i]);
console.log(odd);
}
}
} else {
return null;
}
return odd;
};
oddNumbers(1, 2, 34, 54, 55, 34, 32, 11, 19, 17, 54, 66, 13);
alert(odd);
</script>

Just join your array into string:
else{
return null;
}
return odd.join(', ');

const oddNumbers = (...numbers) => {
var odd = [];
var oddNum
var formatString;
var i;
if (Array.isArray(numbers)) {
for (i in numbers) {
if (isNaN(numbers[i]) === false && (numbers[i] % 2 !== 0)) {
odd.push(numbers[i]);
}
}
} else {
return [];
}
return odd;
};
var result = oddNumbers(1, 2, 34, 54, 55, 34, 32, 11, 19, 17, 54, 66, 13);
console.log(result.join(', '))

Related

Function that inserts a new value in the middle of an array? [duplicate]

This question already has answers here:
array.splice(index, 1) returns array with removed item
(3 answers)
Closed 4 months ago.
I have to use a.splice(index, 0, value) to solve.
this is what I have so far, but the value for final is an empty array(i initialized to null for debugging purposes); I think the problem is with my splice, because my output is just an empty array but i'm pretty sure my syntax is correct.
Input
a == [7, 10, 15, 54]
x = 99
Output:
[7, 10, 99, 15, 54]
function solution(a, x) {
let count = a.length+1
let mid = count/2
let final = null
if (mid % 2 === 0) {
final = a.splice(a[mid], 0, x)
} else {
let middle = mid - 1
final = a.splice(a[middle], 0, x)
}
return final
}
Edit:
I see the comment and have amended the code to this:
let count = a.length+1
let mid = count/2
if (mid % 2 === 0) {
a.splice(mid, 0, x)
} else if (mid % 2 == 1) {
let middle = mid-1
a.splice(middle, 0, x)
}
return a
}
but this input fails because it doesn't want to insert the new value?
**Input:
a: [64, 38, 22, 27, 62, 41]
x: 90
Output:
[64, 38, 22, 27, 62, 41]
Expected Output:
[64, 38, 22, 90, 27, 62, 41]**
Reading offical document of splice(),we can find below description:
Return value
An array containing the deleted elements.
If only one element is removed, an array of one element is returned.
If no elements are removed, an empty array is returned.
Since you are not delete element,that's the reason,so you need to return the element directly
function solution(a, x) {
let count = a.length+1
let mid = count/2
if (mid % 2 === 0) {
a.splice(mid, 0, x)
} else {
let middle = mid - 1
a.splice(middle, 0, x)
}
return a
}
let data = [7, 10, 15, 54,55]
let x = 99
console.log(solution(data,x))
First splice modify the original array. So you will have to return the original array and there is no need of final variable here. Secondly you have to use Math.floor or Math.ceil as mid - 1 will still be a floating point number and lastly a[middle] in a.splice(a[middle]...) need to be replaced only with middle
function solution(a, x) {
let count = a.length + 1
let mid = count / 2
let final = null
if (mid % 2 === 0) {
a.splice(a[mid], 0, x)
} else {
let middle = Math.ceil(mid - 1);
a.splice(middle, 0, x)
}
return a;
}
console.log(solution([7, 10, 15, 54], 99))

Check an number in an array is a powers number

How to check which number is a power in this array?
arr = [16, 32, 72, 96]
output: [16, 32] because 16 = 4^2 and 32 = 2^5
It's not a solution about power of 2, it's about power of n.
This is my actual code :
let array1 = [16, 32, 72];
function findPowofNum(array1) {
// var result = [];
if (array1.length == 1)
return true;
for(let i = 2; i * i <= array1.length; i++) {
let value = Math.log(array1/length) / Math.log(i);
if((value - Math.floor(value)) < 0.00000001)
return true;
}
return false;
}
console.log(findPowofNum(array1));
Can you give me a example for this solution by javascript?
How about
arr = [16, 32, 72, 96].filter(
value => Number.isInteger(Math.log2(value))
)
You can use a custom boolean function to iterate through the elements and append to an empty array as you check like this..
function isPowerofTwo(n){
return (Math.ceil((Math.log(n) / Math.log(2))))
== (Math.floor(((Math.log(n) / Math.log(2)))));
}
let arr= [16, 32, 72, 96];
let values=[]
for(let i=0;i<arr.length;i++){
if(isPowerofTwo(arr[i])){
values.push(arr[i]);
}
}
console.log(values);
const numbers = [16, 32, 72, 96];
const power = numbers.filter(isPowerOfTwo);
function isPowerOfTwo(n)
{
if (n == 0)
return 0;
while (n != 1)
{
if (n%2 != 0)
return 0;
n = n/2;
}
return 1;
}
console.log(power);
To know more about this visit
visit: https://www.geeksforgeeks.org/program-to-find-whether-a-given-number-is-power-of-2/
I think it is 2^4 not 4^2 and what I believe is you want to check if the number is and root of 2 or not
Solution
let arr=[16,32,72,96];
let i=1;
for(i=1;i<=10;i++){ // this loop will run up to 2^10
let k=Math.pow(2,i);if(k==arr[i-1]){
//do whatever you want to do with the number
}
}
This will return true if at least one element y of the array is equal to basepower, where base and power are integers.
The basic idea is to simply try each possible base, compute the value of power needed to make basepower equal to the value, and check to see if power is very close to an integer.
This code only works for positive values, and probably won't work for for value in the upper range near Number.MAX_SAFE_INTEGER, though I really haven't tested it.
let array1 = [7, 13, 72, 27];
function isPowOfNum(val) {
// smallest base is 2, largest is sqrt(val)
for (let base=2; base <= Math.sqrt(val); base++) {
// if val = base ** x then log(val) = x * log(base), x = log(val) / log(base)
// and x is an integer
let power = Math.log(val) / Math.log(base);
if (Math.abs(power - Math.round(power)) < 0.000001) {
return true;
}
}
return false;
}
function findPowofNum(array1) {
if (array1.length === 1)
return true;
return array1.some(isPowOfNum);
}
console.log(findPowofNum(array1));

Solution to Euler Problem 5: My code doesn't work

I have a problem with Project Euler challenge 5. The challenge is based on finding the smallest positive number that is divisible by all the numbers from 1 to 20. This is my code:
let i = 1;
function myFunction (num) {
return i % num == 0
}
while (true) {
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
if (arr.every(myFunction)) {
console.log(i)
break;
} else {
i++
continue;
}
}
The code up to number 16 works fine (720720), but once I add another number to the array, in order (16, 17, 18, ...) it doesn't work anymore. I don't know why, I'm very new to programming. If you could instruct me.
The answer above takes way to long, like he said, quite a few seconds.
This code is longer but takes less than a second to come up with the result.
const divisibleByAllToN = (n) => {
const twoToN = Array(n - 1)
.fill(2)
.map((item, index) => item + index);
let numbersToBeMultiplied = twoToN.filter((item) => {
for (var i = 2; i < item; i++) if (item % i === 0) return false;
return item > 1;
});
numbersToBeMultiplied = numbersToBeMultiplied.map((item) => {
let value = item;
while (value * item <= n) {
value = value * item;
}
return value;
});
return numbersToBeMultiplied.reduce((acc, val) => acc * val);
};
divisibleByAllToN(20);
solved :
you need to return a condition in myFunction in order for array.every to work properly :
let i = 1;
function myFunction (num) {
var result = i / num
return parseInt(result) === result // condition HERE to check if result is an int
}
while (true) {
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
if (arr.every(myFunction)) {
console.log(i)
break;
} else {
i++
continue;
}
}
doing this we get (after about 20 seconds) the right result : 232792560

Referencing same value position in previous array within array of arrays / multidimensional array

I am currently working with 2 functions, one returns an array of arrays (looking like this [[63,2],[74,3]]
At this time I have this:
let thermostatTempArray = [71, 72, 63, 74, 75, 76, 77, 78, 79, 80, 79, 78, 77]
// index 2,3,4,5 = 63,74,75,76 === these indexes should return
// index 10,11,12 = 79,78,77 === these indexes should not return when successful
let coolingCallsArray = [2, 3, 4, 5, 10, 11, 12,]
function findValuesByIndex(indexGivenArray, valueGivenArray) {
const matchedArray = []
valueGivenArray.forEach(function (valueGiven,index) {
const indexGiven = indexGivenArray[index]
if (indexGiven !== undefined) {
const matchingValue = valueGivenArray[indexGiven]
matchedArray.push([matchingValue, indexGiven])
}
})
return matchedArray
}
const coolingVals = findValuesByIndex(coolingCallsArray, thermostatTempArray)
function findOverheatingTerminals(matchedArray) {
overheatingTerminalsArray = []
matchedArray.forEach(function(match,index) {
const [matchingValue,matchedIndex] = match
console.log(`Value: ${matchingValue} Index: ${matchedIndex}`)
const prevMatchingVal = match[[0]]
console.log(prevMatchingVal)
} )
}
const overHeatingTerminals = findOverheatingTerminals(coolingVals)
console.log(overHeatingTerminals)
What I am looking to do is compare the previous matching value (what might look like matchingValue[index-1] if it was in the same array) with the current value (i.e compare 74 with 63) - ONLY if the 2nd number in the array is successive (if it was [[63,2], [74,4] dont compare)I am just unsure how to get the variable right so I can even refer to the previous values.
I ended up going up an array (to the matching arrays previous index) and destructuring it like this
function findOverheatingTerminals(matchedArray) {
const overheatingTerminalsArray = []
matchedArray.forEach(function (match, index) {
const [matchingValue, matchedIndex] = match
const prevMatchingArr = matchedArray[index - 1]
if (prevMatchingArr !== undefined) {
const [prevMatchingval, prevMatchindex] = prevMatchingArr
if (matchingValue > prevMatchingval && matchedIndex === prevMatchindex + 1) {
overheatingTerminalsArray.push(matchedIndex)
}
}
})
return overheatingTerminalsArray
}
exports.findOverheatingTerminals = findOverheatingTerminals

Trying to find if a number exists in my array through input

I am trying to find a number by using the input to search in the array.
Got any idea why this does not work?
Every time i run the code i only get the message:
"Number does not exist"
var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var number = document.getElementById("find").value;
var svar = "";
function exists(){
for(i=0; i < arr.length; i++){
if(parseInt(arr[i]) == parseInt(number)){
svar++;
document.getElementById("existsArray").innerHTML = tall + "Number exists";
} else {
document.getElementById("existsArray").innerHTML = tall + "Number does not exist";
}
}
}
<p id="existsArray"></p>
<input placeholder="what number would you like to find?" id="find" type="number">
<button type="button" onclick="exists()">Finn tallet</button>
I replaced your for loop with indexOf
If you still want to use the loop you should break when you find the matching number
var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var svar = 0;
function exists() {
var number = +document.getElementById("find").value;
if (arr.indexOf(number) !== -1) {
svar++;
document.getElementById("existsArray").innerHTML = "Number exists";
} else {
document.getElementById("existsArray").innerHTML = "Number does not exist";
}
}
<input type="number" id="find" />
<button onclick="exists();">Does it exist ?</button>
<p id="existsArray"></p>
If you want to get the number of occurrence you should use this :
var occurrences = arr.filter(function (num) {return num === number;}).length
So your problem is that you don't exit the loop when you find the matching number. As a result, unless the number you are looking for is the very last number in your array, it will keep looping and the else clause will execute.
function exist() {
var number = parseInt(document.getElementById("find").value,10);
for(i=0; i < arr.length; i++){
if (exists === arr[i]) {
// number exists
break; // <-- this is important another alternative would be to just
// return at this point if the function doesn't do anything else
}
else {
// this number doesn't match, so we'll keep searching
}
}
}
Of course, this is much easier if you just use the built in functions Array.prototype.find or Array.prototype.indexOf
You can also use a filter to keep only values in the array wich match with input :
var arr = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var input = "65";
var result = arr.filter(item => item === parseInt(input));
if (result.length === 0) console.log("number doesn't exist");
else console.log("number exists");
I've made some modifications to your code up front to help isolate your test case. If you look at this rework of your existing code, you'll see you get a message for each of your array elements, ending with "Number does not exist", which was your original problem. This is because that's the last message, overwriting your previous positive results.
var number = "42";
//var svar = "";
var svar = 0;//changing this from a string to a number. Can't ++ a string.
var myArray = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
/*
* #param {String} num - Passing the value that I'm looking for, rather than
* trying to pull it from elsewhere. This makes this much easier to test later.
* #param {Array} arr - Array of integers to search
*/
function exists(num, arr) {
for(i=0; i < arr.length; i++){
//if(parseInt(arr[i]) == parseInt(number)){
//No need to use parseInt here on the array. It's already a Number.
if(arr[i] == parseInt(number)){
svar++;/* I don't see any reason to be incrementing this. Perhaps it's elsewhere
in your implementation? */
//Using console.log() instead of elements not included in your code sample
console.log("Number exists");
} else {
//This keeps overwriting the above, except in a case where
//the last number would be a match!
console.error("Number does not exist");
}
}
}
exists(number, myArray);
If you want this to work as intended, you can either can eliminate your "Number does not exist" else branch, which will cause the positive message to remain, and you can leave your default text as "Number does not exist", or you simplify it, using what I'd recommend:
var number = "42",
number2 = "101",
myArray = [18, 21, 34, 42, 65, 63, 39, 13, 15, 24, -1, 14, 15];
var existsSimple = function (num, arr) {
return myArray.filter(function (itemNum) {return itemNum === parseInt(num);}).length > 0;
};
console.log('Number exists: ' + existsSimple(number, myArray));//true
console.log('Number exists: ' + existsSimple(number2, myArray));//false

Categories

Resources