Is using an Array.map as a foreach good practice? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm already using an Array.map, but with the same data, I need to do some other calculations. Should I do those calculations within the map or do it in a for each after the map?
return res.data.map(function (obj) {
if(obj.status.id == 6 || obj.status.id == 5){
dateDifference(obj.created_at,obj.closed_at);
}else{
$scope.open++;
}
return {
"id":obj.id,
"subject": obj.subject,
"requester": obj.requester.name,
"assigned": obj.assigned ? obj.assigned.name : '',
"priority": obj.priority.name,
"status": obj.status.name,
"category": obj.category.name,
"created_at": moment(obj.created_at).utcOffset("06:00").format('lll'),
"updated_at": moment(obj.updated_at).utcOffset("06:00").format('lll')
}
})

I don't see it as a 'good practice', but I don't see it as a bad practice either. Fact is, .map() is designed to both iterate and create a new resulting array.
Perhaps the answer lies in its definition.
From the JS website :
"The map() method creates a new array with the results of calling a
provided function on every element in this array."
From the PHP website (for fun) :
"array_map() returns an array containing all the elements of array1
after applying the callback function to each one."
Nothing keeps you from doing what you want in that callback function.
If you, personnally, are not comfortable doing that, you could achieve the same thing doing a 'for each' while building your own new array. Which is probably what I would do in your specific case. I'd rather do that than have to iterate 2 times over my array.
Though, as Bergi mentionned, it is a better practice to iterate twice over the array if it makes sense sematically.
If performance were to become an issue (iterating twice on a long array). Here is what I would be inclined to do :
for (var i=0; i<myArray.length; i++) {
doStuffA(myArray[i]);
doStuffB(myArray[i]);
}
which is quite clear semantically. Instead of iterating twice.
Of course, some pleople might (will probably) disagree with me.

Related

React -- Why does this line append rather than add [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 15 days ago.
Improve this question
I have other ways of doing the same thing .. So I am not looking for a different solution to this problem ... I am looking for an explanation as to why if I have defined a integer, it still concatenates with .map as if it were a string.
I have a basic set of data retrieved from an API:
"data":["8","8","12","1","7","4","2"]
If I map it using
let count = response.data.metrics.data.map((item) => + parseInt(item));
I am having a hard time understanding why it's treating this as a string returning
88121743
When I feel like because I am parsing it as an integer it should add and come out with 42.
Is this just an issue just using .map? Can shortcut math functions be used here?
Here is my Reproducible Example
Your current approach using Array#map creates a new array with each element converted to a number. React renders this array as multiple text nodes, so it looks like a single string.
To sum the values, use Array#reduce with parseFloat/parseInt, the Number function, or the unary plus operator to convert each string to a number.
const visitCount = data.reduce((a,b) => a + parseFloat(b), 0);

Not quite understand what does the i stand for in forEach function in my code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am using this method to find the frequency of words, however i am a bit confused with the whole code.
Here is the code:
function check(){
var word = document.querySelector('textarea').value.split(" ");
frequency ={};
word.forEach(function(i){
console.log(i)
if(!frequency[i]){
frequency[i] = 0;
}
frequency[i]+=1
})
console.log(frequency)
}
<textarea></textarea>
<button onclick = 'check()'>check</button>
I just wonder what does the i stand for and what does the frequency[i].
Could someone explain to me a little bit because I think this code is not quite friendly for me, the beginner.
foreach iterates over array, and as paramter has function into which is passed as parameter actual element of array. So i in this function is actual element of 'word' array.
for object frequency is frequency[i] the i'th element. At start, this object is empty, so frequency[i] will be undefined, but in foreach loop you filling this object with some values so in next iterations there may by some values

Is the map function inefficient? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm learning a little bit of efficiency code.
I do the next code.
The map function returns a result slower.
https://i.stack.imgur.com/oVSBw.png
i'm doing something wrong?
var user = [
{
name: 'Sebastian',
age: 19
},
{
name: 'Gabriela',
age: 51
},
{
name: 'Julian',
age: 19
}
]
console.time('map');
user.map(item => console.log(item.name));
console.timeEnd('map');
console.log('\n');
console.time('for');
for (var i = 0; i < user.length; i++) {
console.log(user[i].name);
}
console.timeEnd('for');
Fundamentally, JavaScript is not a programming language where doing something in the cleanest way is also the most efficient way. C, D, and C++ are languages that are designed that way.
If you look into V8 internals, you'll notice that map has to deal with array holes, making it slower.
No it is not inefficient. You are comparing map with normal for. .map adds a layer of abstraction from the outside scope with results in an increase in the execution time when compared with the normal for.

Can someone help explain why I get this 'Value is not what was expected' error with Javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm working on beefing up my Javascript skills with some katas on codewars. Here is one such kata:
At a job interview, you are challenged to write an algorithm to check if a given string, s, can be formed from two other strings, part1 and part2.
The restriction is that the characters in part1 and part2 are in the same order as in s.
The interviewer gives you the following example and tells you to figure out the rest from the given test cases.
For example:
'codewars' is a merge from 'cdw' and 'oears':
s: c o d e w a r s = codewars
part1: c d w = cdw
part2: o e a r s = oears
Here is my solution that I am working on:
function presentInString(element, index, array) {
return string.includes(element);
}
function isMerge(s, part1, part2) {
string = s;
var mergedParts = (part1 + part2).split('');
mergedParts.every(presentInString);
}
My approach is simple, I get passed in a string 'codewars' and with parts 'cdw' and 'oears' The above methods should return true because all of the characters are in the string. but I keep getting a Value is not what was expected error. I must be using the .every method wrong but I'm not sure how. I pretty much based it off of the Javascript MDN docs. Could someone pinpoint what I'm doing wrong?
It's a kata in progress by the way and I haven't tested all edge cases. Some cases will fail.
Additionally, do I have to create another function to pass into .every? I would rather just right the logic in the scope of .every instead of writing another function to pass off to.
I can't vouch for your overall algorithm, but the problem with isMerge is that it doesn't use the return value of every and doesn't return anything. You probably wanted:
return mergedParts.every(presentInString);
as the last line, which makes the return value of isMerge whatever every returns (true if presentInString returns a truthy value for each element, false if it doesn't).

Iterating over an array with `every` [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
The book that I'm studying says about iterating over arrays with every that:
The function these methods use must follow one ruleā€”it must accept
three arguments like the following code:
function functionName(value, index, array) {
// do something here
}
Does that mean that I must always use 3 arguments? If so then why does this code work?
var numbers = [ 1, 2, 2 ];
function isLessThan3(value) {
var returnValue = false;
if (value < 3) {
returnValue = true;
}
return returnValue; }
document.write(numbers.every(isLessThan3));
There is no limitation on how many arrguments you can put in a function with Javascript.
you have a very good explenation about this topic in the next answer by #Niet the Dark Absol
https://stackoverflow.com/a/22747272/1283672
i believe that the book was reffering to something more specific within it's scope.
And just to be clear you can put no arrgs in a function either.
It's a bit ugly, the code, you have, but there is help. You might use the following without a temporary variable. Just return the result of the comparison.
function allLessThan3(value) {
return value < 3;
}
var numbers = [1, 2, 2];
console.log(numbers.every(allLessThan3));
No, you can use from 0 to 3 arguments

Categories