funtion wont print enter forloop referencing an array [duplicate] - javascript

This question already has answers here:
Does return stop a loop?
(7 answers)
Closed 9 months ago.
I somehow can't get my for loop inside of a function to print elements in an array.
could someone point out why javascript is not allowing the iteration to occur and only printing the first element?
const data1 = [17, 21, 23];
function printForecast(array) {
for (let i = 0; i < array.length; i++) {
let dayVsDays = i <= 1 ? 'day' : 'days'
return `The temp is ${array[i]}ÂșC in ${[i+1]} ${dayVsDays}`;
}
}
console.log(printForecast(data1))

Don't use return inside a loop unless you want to return the result of an specific iteration; this is why you only get the first iteration.

Related

How can I create an array containing 1...X without loop [duplicate]

This question already has answers here:
How to create an array containing 1...N
(77 answers)
Closed 20 days ago.
how creating a JavaScript array containing 1 through to x where x is only known at runtime without the loop.
var arr = [];
for (var i = 1; i <= x; i++) {
arr.push(i);
}
This is a duplicate of this issue
here is the answer anyway
const arr = [...''.padEnd(N)].map((_,i)=>i+1)

Fastest and Most Efficient way to check for duplicates in a javascript array [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
In Javascript, how do I check if an array has duplicate values?
(9 answers)
Checking for duplicate strings in JavaScript array
(13 answers)
Closed 5 months ago.
I am writing a javascript function that takes a nested array and returns the numbers that occurs more than once in that array.
I believe my function is accurate (meaning that it passes their "Correctness test" ) but i am after efficiency, how efficient is this code?
For example - Lets call the name of the function deepSort(nestedArray) where nestedArray is the nested array parameter
function deepSort(nestedArray) {
const flatArr = nestedArray.flat().sort();
let results = []
for (let i = 0; i < flatArr.length - 1; i++) {
if (flatArr[i + 1] == flatArr[i]) {
results.push(flatArr[i]);
}
}
return (results.filter((item, index) => results.indexOf(item) === index)).join()
}
const a = deepSort([[1,3,4,5], [4,7,9,1,3], [2,3,5], [1,2,3,4]]) // Returns 1,2,3,4,5
console.log(a);
const b = deepSort([[1,2,3], [4,5], [6,7,8], [2,9,0]]) // Returns 2
console.log(b);
const c = deepSort([[2,7,9], [4,3], [9,6,5], [1,4,3]]) // Returns 3,4,9
console.log(c);
Can this code be optimized any more for speed and efficiency when handling extremely large values of data?

How to create an array with a set amount of elements inside all set to 0? (Javascript) [duplicate]

This question already has answers here:
Most efficient way to create a zero filled JavaScript array?
(45 answers)
Closed 1 year ago.
If I want to create an array containing a piece of data for every minute of the year (525,600 elements for 365 day year) or (524,160 elements for 364 day year) is there a way to create an array with a set amount of elements inside all set to a value of 0?
const minutesOfTheYear = [];
minutesOfTheYear[0] = 0;
minutesOfTheYear[1] = 0;
minutesOfTheYear[2] = 0;
/* ... */
minutesOfTheYear[525,599] = 0;
I think I could use a for loop, setting the amount of loops to 525,600 and the index of the array amended to add by 1 each time, but what is the proper way to declare the new values within a for loop? Would this work?
for (let i = 0; i< 525599; i++) {
minutesOfTheYear[i] = 0;
}
Or is there a line of code that just declares the size of the array and auto populates?
Use Array.from():
const result = Array.from({ length: 524160 }, () => 0);
console.log(result);
The second argument is a map function - it is run once for each item in the array, and it must return the value for that item. In this example, it's simply returning 0.
Array(100).fill(0) // length is 100

When uniquely updating an object in an array in Javascript, the objects values are all changing [duplicate]

This question already has answers here:
How to update one Javascript object array without updating the other [duplicate]
(3 answers)
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 3 years ago.
I currently have an array of objects called posts.
for(var i = 0; i < posts.length; i++){
let post = posts[i]
let { item, category } = post
let postCollections = categories[category]
for(var col in userCollections[category]){
let items = userCollections[category][col].items
if(items && col){
postCollections[col]['item'] = item
console.log("HERE!, item)
if(item in items){
postCollections[col]['joined'] = true
}else{
postCollections[col]['joined'] = false
}
}
}
posts[i]['collections'] = postCollections
}
When this is run, the print out for "HERE!" shows the item value is unique. When I print out posts and look at the value for key items they all show the same item.
This was a tough solve. Turns out the line where I set postCollections was using the same object over and over again. Copying the object like this has done the trick:
let postCollections = JSON.parse(JSON.stringify(categories[category]));

Pushing elems into an array conditionally [duplicate]

This question already has answers here:
Array.push() if does not exist?
(30 answers)
Remove duplicates form an array
(17 answers)
Closed 4 years ago.
I have a simple array with a few elems & a new elem , trying to check the elems with a function , push the new elem into the array if not already present & ignore it if it is.
I created a function with an if /else statement but the code always adds the new item to the array.
var arr=['a','b'];
var newElem='c';
function f(){
for(var i=0; i<arr.length; i++){
if(arr[i] == newElem){ console.log('Exists');return }
else {arr.push(newElem);console.log(arr); return }
}
}
f();
The code works fine if the new item not present in the array but if it's ,the new elem still being pushed into the array?
Pls anyone could help , don't want to ask the teacher , it looks so simple ?
Check if element exists first like so:
const arr = ['a', 'b'];
const newElem = 'c';
if (arr.indexOf(newElem) === -1) {
arr.push(newElem);
}

Categories