This question already has answers here:
Create an array with random values
(24 answers)
Closed 3 years ago.
This is more like a silly question but I have to ask it.
It is a good practice to call an array function like map without arguments?
Let's say I already have an array 'x' on my code with a specified length and I want to make another array with the same length but with different content.
For example:
function generateRandomContent() { ... }
const x = [1, 2, 3, 4, 5]
const y = x.map(() => generateRandomContent())
// or
const z = Array(x.length).fill().map(() => { ... })
Of course I could pass an argument and never use it, but it is there a good way and a bad way to do it?
You should not use .map here. A mapping operation is when you take some input and generate a new output. So you have a relation that looks like this x -> y for a single element, then you apply it to the entire array to generate a new array using the same mapping rule:
const input = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100];
//mapping relationship
const toCharacter = x => String.fromCharCode(x);
const result = input.map(toCharacter);
console.log(result.join(''))
If you just want to create a new array based on the length of the original but with totally unrelated content, then you are better off to use Array.from which can create an array with a given size and takes a second argument that will fill it with content:
function generateRandomContent() {
return Math.floor(Math.random() * 100);
}
const x = [1, 2, 3, 4, 5]
const y = Array.from({length: x.length}, () => generateRandomContent());
//or just pass the function reference
const z = Array.from({length: x.length}, generateRandomContent);
console.log(y);
console.log(z);
Related
Referring to this picture, the first array is x-coordinate and second array is y-coordinate. The blue boxes will be the node number for each (x,y). if the point has been labelled before, it will remain with the same node number that was assigned to it previously. And if the point has not been labelled before and is new, it will be assigned a new node number :) For my attempt, I am trying to find the index of all mirror coordinates and the number of mirror coordinates present with the code below. However, I am unsure what the next step should be to get the value of the blue boxes in an array. This is in javascript. Any guidance will be appreaciated :)
for (let i=0;i<jaja+1;i++){
if ( (x_all[arr[m]+i]==x_all[arr[m]-i]) ){
}
}
This is a fairly straightforward 'zip' with an added map of previously seen points, here tracked in an object keyed by the JSON string of each point, and retrieving/setting the next id using logical nullish assignment (??=).
const xs = [102, 152, 202, 252, 202, 152, 302, 10, 332, 10, 1];
const ys = [100, 50, 60, 70, 60, 9, 3, 2, 1, 2, 100];
let seen = {}, count = 1;
const result = xs.map((x, i) => {
const point = { x, y: ys[i] };
const id = (seen[JSON.stringify(point)] ??= count++);
return { id, ...point };
})
console.log(result)
see more 'zip' discussion here: Javascript equivalent of Python's zip function
This question already has answers here:
Split array into chunks
(73 answers)
Closed 1 year ago.
am wonder how to do this one, can you help me to learn how to think and solve this kind of problem, please?
in this example i will use 8 like N
let original = [1,2,3,4,5,6,7,8,9,10];
//to
let modified = [[1,2,3,4,5,6,7,8],[9,10]]
for example if i use a Array.slice and i have more than the example number like 19 elements inside original i need to create a new array inside to modified
and should be look like this :
[[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16],[17,18,19]]
is dynamic
Use .slice() to pull out the parts needed.
You should read the docs for slice.
The way to think about this is "I want part of the array". In JavaScript you retrieve part of an array by using .slice().
Since you have an unknown number of elements, you can use a while loop and shorten the array on each loop. The loop should exit when there are less elements than the size you want (8). Then, add the remaining elements. All of this still using slice.
let original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19];
let out = [];
while (original.length > 8) {
out.push(original.slice(0, 8));
original = original.slice(8);
}
out.push(original);
console.log(out);
I will do that this way:
let original_1 = [1,2,3,4,5,6,7,8,9,10]
, original_2 = [1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19]
const arrayCut = (arr, count) => arr.reduce((a,c,i)=>
{
let aN = Math.floor(i/count)
if (!(i%count)) a.push([])
a[aN].push(c)
return(a)
},[])
let mod_1 = arrayCut( original_1, 8 )
, mod_2 = arrayCut( original_2, 8 )
console.log('mod_1', JSON.stringify(mod_1))
console.log('mod_2', JSON.stringify(mod_2))
.as-console-wrapper { max-height: 100% !important; top: 0; }
This question already has answers here:
adding custom functions into Array.prototype
(7 answers)
Closed 3 years ago.
How can I create a functions within JavaScript, that i can then use and chain with others to get results from an array.
I have tried creating a class with multiple methods that can be chain together but that wont allow me to call the functions directly on the array itself.
Example:
[23,45,87,89,21,234,1,2,6,7].CustomFuncEvenNumbers().CustomFuncOrderNumbers()
You can create the custom function using prototype but to chain another function you need to explicitly return from your custom function , else it will return undefined
let arr = [23, 45, 87, 89, 21, 234, 1, 2, 6, 7];
Array.prototype.CustomFuncEvenNumbers = function() {
return this.filter(function(item) {
return item % 2 === 0
})
}
let k = arr.CustomFuncEvenNumbers().map(item => item * 2);
console.log(k)
This question already has answers here:
Does JavaScript have a method like "range()" to generate a range within the supplied bounds?
(88 answers)
Closed 4 years ago.
Is it any way to create an array a selected size(for example 10) and immediately on the spot fill in it with some numbers specified pattern (1, 2, 3, OR 2, 4, 6 and so on) in one statement in JS?
let arr = new Array(10).fill( (a) => {a = 1; return a++; } );
console.log(arr); // Should be 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
In other words can I pass a some patern or function to method fill insted of a single value.
Actually there's much nicer idiom to create ranges: a spreaded Array constructor:
[...Array(n)]
creates an array of n undefined values. To get 0..n-1, just pick its keys:
[...Array(n).keys()]
for arbitrary ranges, feed it to map:
r = [...Array(10)].map((_, i) => i + 1)
console.log(r)
see here: Does JavaScript have a method like "range()" to generate an array based on supplied bounds?
old answer:
yep, you're looking for Array.from:
r = Array.from({length: 10}, (_, i) => i + 1);
console.log(r)
How does this work? .from inspects its first argument (which can be any object) and picks its .length property. Then, it iterates from 0 to length - 1 and invokes the second argument with two parameters - a value (which is undefined unless the first argument contains a corresponding numeric property) and an index, which takes values from 0...length-1. In this example, we have a function that just returns an index + 1, thus giving us 1..length.
Here's a useful wrapper for the above:
let range = (from, to) => Array.from({length: to - from + 1}, _ => from++);
console.log(range(1, 10))
For ES5, the idiom is Array.apply(null, {length:N}):
r = Array.apply(null, {length: 10}).map(function(_, i) {
return i + 1
})
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Return array value with forEach() [duplicate]
(1 answer)
Closed 5 years ago.
So there are a lot of questions about iterating over an array, but I found none that says how to get the transformed array back as the left side variable. I can always do a standard for loop with indicies but I was wondering if I could use something like a .foreach that would return a transformed array.
Psedo example: I have an array points which are made up of an object Phaser.Point
Such that I can write the following code
x = new Phaser.Polygon(points.foreach(function (point) {
return new Phaser.Point(point.x+5, point.y+5)
});
new Phaser.Polygon takes an array of Phaser.Point objects
In this case, you may want to use Array.prototype.map(). Here is an example from MDN:
var numbers = [1, 5, 10, 15];
var roots = numbers.map(function(x) {
return x * 2;
});
// roots is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
In your case:
x = new Phaser.Polygon(points.map(function (point) {
return new Phaser.Point(point.x+5, point.y+5)
});
References:
Array.prototype.map()
You can use Array.map. Array.map returns new array.