how I can solve aperture function in javascript? [duplicate] - javascript

This question already has answers here:
How to create windowed slice of array in JavaScript?
(3 answers)
Closed 3 years ago.
I want solve a function called aperture which accept a number and an array that should return new array that should be composed of subarrays the size of the number with consecutive elements, for example aperture:
(3, [1, 2, 3, 4, 5]); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

Create an empty array whose length is equal to the given number and use reduce() on it.
const aperture = (num,arr) => [...Array(num)].reduce((ac,_,i) => {
ac.push(arr.slice(i,num+i));
return ac;
},[])
console.log(aperture(3,[1,2,3,4,5]))

Related

How do make a JSON from an array [duplicate]

This question already has answers here:
Convert array to JSON
(12 answers)
Closed 6 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Array:
myArr = [[1, 2, 3], [4, 5, 6]]
Expected output:
newArr = "[[1, 2, 3], [4, 5, 6]]"
I have tried:
myArr.toString()
String(myArr)
myArr = `${myArr}`
What I got by doing the above methods:
'1,2,3,4,5,6'
I gather what you would like to achieve is more or less serialization. We could use JSON.stringify in JavaScript to serialize an Array.
const array = [[1, 2, 3], [4, 5, 6]];
const serializedArray = JSON.stringify(arr));
To deserialize the Array, JSON.parse could be used.
const originalArray = JSON.parse(serializedArray));
JSON.strinify is what you need.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
const myArr = [[1, 2, 3], [4, 5, 6]];
const myArrString = JSON.stringify(myArr);
console.log(`Here is my string: ${myArrString}`);
use JSON.stringify(myArr);
you can find out more on below link
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Sorting array with sort function [duplicate]

This question already has answers here:
How does Javascript's sort() work?
(8 answers)
How does sort function work in JavaScript, along with compare function
(7 answers)
How does JavaScript's sort (compareFunction) work? [duplicate]
(3 answers)
Closed 1 year ago.
I got question today, that I couldn't answer. I would appreciate if you could just explain it to me. Why my array doesn't output [1, 2, 3, 4, 5] but only [2, 3, 4, 5]?
This is the code:
let numbers = [1, 2, 3, 4, 5]
let order = numbers.sort((a, b) => {
console.log(a);
});
But when I use this code, it works perfectly fine
let numbers = [1, 2, 3, 4, 5]
let order = numbers.sort((a, b) => {
return a;
})
console.log(order);
It doesn't output [2, 3, 4, 5] it outputs 2, 3, 4 and 5 each in a separate step of the iteration. If you also log order you'll see that the array still contains [1, 2, 3, 4, 5]. The comparator function receives two elements of the array that it compares to each other. That way it knows in which order those elements should be. If you only log a and not b, you'll wont see all the information that is passed to the comparator. If you log both a and b, you'll see that also 1 is passed, to parameter b.
let numbers = [1, 2, 3, 4, 5]
let order = numbers.sort((a, b) => {
console.log('Comparing', a, b);
});
console.log('Final result', order);
Keep in mind that the comparator function should return either a positive number when a is greater than b, a negative number when a is less than b and 0 when both elements are equal to each other. The above comparator function doesn't return any value at all, so it might not do what you expect it to do.
(Also your snippet that "works perfectly fine" doesn't follow that contract. It returns a positive number for each element, so it is basically saying that every element is greater than every other element.)
The sort() method sorts the elements of an array in place and returns the sorted array.
[1, 2, 3, 4, 5].sort((a, b) => {
console.log({a, b}); // a is secondItem, b is firstItem of an array
return -1; // return -ve value for DESC and truthy value for ASC order
});
Output will be
{a: 2, b: 1}
{a: 3, b: 2}
{a: 4, b: 3}
{a: 5, b: 4}
sort output: [5, 4, 3, 2, 1]

Most efficient way to flatten Array<Array<T> | T> in JavaScript [duplicate]

This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 3 years ago.
I want to create a function that accepts an array of both arrays and literals (or maybe objects) and flattens it to a single dimensional array. For example a valid input would be [5, [2, 3], 7, [9, 0, 1]], and the output of that input should be [5, 2, 3, 7, 9, 0, 1].
This is the code I have so far. There is nothing wrong with it, I just want to make sure it's as efficient as possible (it also needs to be es5 compatible).
function flattenArray(list) {
var result = [];
for (var index = 0; index < list.length; index++) {
result.push(list[index] instanceof Array ? list[index] : [list[index]]);
}
return [].concat.apply([], result);
}
console.log(flattenArray([5, [2, 3], 7, [9, 0, 1]]));
How about simply using Array.flat
function flattenArray(list) {
return list.flat()
}
console.log(flattenArray([5, [2, 3], 7, [9, 0, 1]]));
This seems to be second fastest ( based on the test link attached below ) and ES5 compatible
console.log([].concat.apply([],[5, [2, 3], 7, [9, 0, 1]]))
Performace test
Cocerning your code: There is no sense in wrapping single elements into arrays, .concat will handle them correctly, in other words:
[1].concat([2], 2)
just works, there is no need for wrapping 2 into [2]. That turns your code into a oneliner.

Calling Array.prototype.map with Math.max returns array of NaN [duplicate]

This question already has answers here:
Why does parseInt yield NaN with Array#map?
(8 answers)
Closed 4 years ago.
Why does [1, 2, 3].map((x) => Math.max(x)) return [1, 2, 3]
yet [1, 2, 3].map(Math.max) returns [NaN, NaN, NaN] ?
I would have thought since [1, 2, 3].map(Number) returns [1, 2, 3], the same would true for using Math.max in the same way.
Especially since Math.max(3) == Number(3).
It's because map invokes the callback with three arguments:
The current array element.
The index of the current element.
The array map was called on.
So [1, 2, 3].map(Math.max) is not equivalent to [1, 2, 3].map((x) => Math.max(x)), but to [1, 2, 3].map((x, i, arr) => Math.max(x, i, arr)).
And Math.max(1, 0, [1, 2, 3]) is NaN because the [1, 2, 3] array becomes "1,2,3" when stringified, which becomes NaN when converted to a number.
You can use spread operator:Math.max(...[1,2,3])

JS: Make new array form duplicate values [duplicate]

This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Compute intersection of two arrays in JavaScript [duplicate]
(4 answers)
Finding matches between multiple JavaScript Arrays
(13 answers)
Closed 5 years ago.
Let's take two arrays for example:
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
Now there is duplicates as we see 4 and 5. How to make new array from them instead of getting rid of them. What is the easiest solution?
So new array should be like:
newArray = [4, 5]
Thank you guys in advance!
You can do it using Array.filter() and Array.includes()
let a = [1, 2, 3, 4, 5];
let b = [4, 5, 6, 7, 8];
let arr = a.filter(function(x){
return b.includes(x);
})
console.log(arr);

Categories

Resources