In what cases do javascript developers use the map() method? - javascript

I'm learning about the map() method right now and I understand very basic examples.
var numbers = [2, 4, 6];
var double = numbers.map(function(value) {
return value * 2;
});
My question is, in what cases do developers use the map() method to help solve problems? Are there some good resources with real world examples?
Thanks for the help!

As #Tushar referred:
The map() method creates a new array with the results of calling a
provided function on every element in this array.
So it is basically used when you need to apply certain functionality to every single element of an array and get the result back as an array with the new results.
For example doubling the numbers:
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles is now [2, 8, 18]. numbers is still [1, 4, 9]

It basically helps to shorten your code eliminating the need of using for loop. But do remember it is used when every element of the array is manipulated because map() generates similar length of array provided.
For eg.- in the example you provided doubles will have [2, 8, 18].
where 2 correspond to 1.
4 correspond to 8.
9 correspond to 18.

I recommend you to watch the whole video but your answer is at the 14th minute:
Asynchronous JavaScript at Netflix by Matthew Podwysowski at JSConf Budapest 2015

Related

Why aren't sizes/lengths standardized on similar objects (Array.length vs. Map.size for instance)? [duplicate]

While looking over new changes to JavaScript I noticed that Set and Map use .size instead of .length like arrays would.
This seems like a pointless diversion from what's normal with arrays - just one more thing to remember.
Was there a good design reason for this?
There's a lot of discussion in the esdiscuss thread "Set length property". This was a hotly debated issue, so it's not surprising that you do not necessarily agree with the resolution.
There is a tremendous amount of arguing about this in esdiscuss. Ultimately, the argument that prevailed (as evidenced by the fact that ES2015's Sets have size and not length) was summarized in a post by David Bruant:
...for me 'length' refers to a measurement with something like a ruler. You start at 0 and see up to where it goes. This is very accurate for an array which is an indexed set (starting at 0 and growing) and for arrays as considered in C (continuous sequence of bytes) which ECMAScript arrays seem inspired of. This is probably less relevant for unordered collections such as sets which I'd tend to consider as a messy bag.
And further discussed in a post by Dean Landolt:
Just wanted to jump in and say non-writable length is consistent with String behavior as well, but David makes a good point about length implying metric topology. David's suggestion of count is nice. ISTM what we're talking about is cardinality, but no need to get too silly w/ precision. Though size is just fine with me, and has plenty of prior art.
While apsillers' Jan 27, 2016 answer adds great links, a code example is missing. The size of a set is a read-only getter while that's not the case for arrays which allow modifying the length to truncate the array.
let arr = [1, 2, 3, 4]
arr.length = 2
console.log("modified length array", arr) // [1, 2]
let mySet = new Set([1, 2, 3, 4])
mySet.length = 2
mySet.size = 2
console.log("modified length set", [...mySet]) // [1, 2, 3, 4]
let str = "1234"
str.length = 2
console.log("modified length string", str) // "1234"

Is there any way of converting OpenCV.Mat to array in JavaScript?

I'm working on Mat in OpenCV. However, I need to manually calculate the Mat by myself. Is there is a way of accessing Mat likes 2D array?
const myMat = cv.matFromArray(cv, 3, 3, cv.CV_64F, [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
const newMat = someProcessThatReturnMat(myMat)
/* OpenCV in JS cannot access Mat like this */
const result = someProcess(newMat[1][2], newMat[2][0])
Thank you in advance
Updated: The problem is cv.matFromArray cannot convert 2D array to Mat. You have to use it as 1D array. That's why it never return the correct values. For example:
const myMat = cv.matFromArray(3, 3, cv.CV_64F, [1,2,3,4,5,6,7,8,9])
And then, you can access the value
const value = myMat.doubleAt(1, 2) // row 1, col 2
You need to use the doubleAt(y,x) method.
It's double because the mat's content is CV_64F, not because you want doubles.
You can also use .data64F to access a flat Float64Array of the Mat's data.
OpenCV.js is... rough. It originated from someone's Google Summer of Code and hasn't received significant care since. Documentation amounts to some tutorials; API docs seem to be missing entirely. The "Mat" interface emulated the at() method from C++, badly, instead of looking at numpy (python) or making this access feel "native" to javascript. Overloading the [] operator is possible using a Proxy but that was not implemented.
Here's an example: https://docs.opencv.org/4.x/de/d06/tutorial_js_basic_ops.html
Feel free to browse OpenCV's issues and maybe suggest some improvements.

Array.splice doesn't change the length

I have a function where I delete some parts of an Array using .splice, but when I look about console.log on it's length it hasn't changed.. and with hexdump I also saw that the "deleted" string is still there
e.g.
Sudoku[j][y] = [3, 7]
Sudoku[x][y][k] = 3
function...
Sudoku[j][y].splice(Sudoku[j][y].indexOf(Sudoku[x][y][k]), 1)
console.log(Sudoku[j][y], Sudoku[j][y].length, Hexdump.dump(Sudoku[j][y]))
= [7] 2 /*Zusammenfassung des hex:*/ 3, 7
(the value that shall be deleted comes from an other var, that's why I wrote the part with the "indexOf")
The Sudoku is a 3D Matrix: the first D ans second D are the x and y rows/columns, while the third Dimension is for the rest posibilities
What can I do, to delete the value once and for all?
because I have an IF that needs to know the length of my Arrays...
after I threw a bunch of more console.log into my code I also saw that stuff...
Sometimes...
console.log(sudoku[j][y].length, sudoku[j][y], sudoku[j][y].indexOf(sudoku[x][y][k]))
sudoku[j][y].splice(sudoku[j][y].indexOf(sudoku[x][y][k]), 1);
console.log(sudoku[j][y].length, sudoku[j][y])
Results into:
4 [7, 9] 0
3 [7, 9]
so my newest try was to use an new method instead of splice:
sudoku[x][j][(sudoku[x][j].indexOf(sudoku[x][y][k]))]=sudoku[x][j][sudoku[x][j][sudoku[x][y].length-1]]
sudoku[x][j].length--
It worked in jsfiddle but ain't solved my problems in my real code...
sometimes I saw a "undefined" in my code.. but the bigger problem was that it also left the hexdumps there... so that the lenght, even after I directly said him to get smaller, hasn't changed...
You're splicing an element that is outside of the array:
var arr = [1,2,3];
arr.splice(3,1);//doesn't take anything out of the array
arr.length===3;//true

How to Reduce Two Loops in Javascript for Efficiency

I have a particular array, by which I wanted to check if two values within the array equal the value passed into the function, and if the two integers do, then pass it into a new array.
I have solved this by using two backwards while loops and caching the length as a variable, which seemed to be efficient. However, someone mentioned to me there might be a way to remove the need for one of the loops and making it much more efficient and thus optimizing the BIG O notation.
Any ideas how this could be done? This is what I have...
var intArray = [1, 3, 7, 8, 10, 4, 6, 13, 0],
newArray = [],
i = intArray.length;
function arrayCheck(k) {
while(i--) {
var z = i;
while (z--) {
if (intArray[i] + intArray[z] === k) {
newArray.push(intArray[i]);
newArray.push(intArray[z]);
}
}
}
alert(newArray);
}
arrayCheck(8);
There is an algorithm that solves this problem in linear [O(n)] time. I recommend you check out this SO answer.
Also, as others have stated, marking answers as accepted will make people more likely to answer your questions. You may wish to revisit questions you've previously asked and accept any answers that deserve it.
if you check for number N, and intArray[i] = M, then you need to find a value N-M in the array.
Build an efficient tree search to find values N-M and you can solve this in O(n+logn).

Automatically Generate max 'N' values from javascript array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: min & max Array values?
Generate max 'N' values from javascript array
var arr = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
How to execute 5 max values from this array?
result must be like
10, 9, 8, 7, 6
Check out the Arrays Java API doc. It'll give you some practice in reading up on documentation as well as give you methods to use to solve the homework problem ;)
you can try this
1. first you arrange Array in ascending order.
2. get it's Length.
3. get last 5 Digits whose u have required.
i thinks this is helpful to you.
..! cheers

Categories