Get intermediate array in Javascript Map function - javascript

Is there a way to get the array being generated by the map function, inside the map function? For e.g.
let arr = [1, 2, 3, 4];
arr.map(item => {
console.log(currentArray);
return item * item;
}
So, in the above example, if at line 3 (currentArray), I want below output, how can I get that.
[1]
[1, 4]
[1, 4, 9]
The "array" parameter in map callback, returns the original array on which map function is called.
Or do I need to go conventional for loop route to achieve this?

You could map the squares by using a closure over ta temporary result set.
let array = [1, 2, 3, 4],
result = array.map((t => v => t = [...t, v * v])([]));
console.log(result);

You can use reduce function as follow,
let arr = [1, 2, 3, 4];
arr.reduce((acc, item)=>{
acc.push(item*item);
console.log(acc);
return acc;
}, []);
// SINCE YOU ARE ASKING HOW TO DO IT USING MAP
console.log('*******************************')
let arr1 = [1, 2, 3, 4];
const currentArray = [];
arr1.map(item => {
currentArray.push(item * item);
console.log(currentArray);
return item* item;
})

You can use the reduce instead of the map, but you do not have to by the way. Anyways, then you will have your accumulator as the first argument to the reducer callback. The variable accumulator will hold the intermediate states of the value to be returned.
let arr = [1, 2, 3, 4];
let result = arr.reduce((accumulator, item) => {
console.log("currentArray accumulator: ", accumulator);
return [...accumulator, item * item];
}, []);
There is a neat another answer around which uses map and do what you want. So, yes it is possible to achieve same with map and reduce is a convenience function that actually is a special case map function itself.

Related

Map method in React and native js

I'm having trouble understanding how the map method works in React.
In javascript, the map returns a new array and doesn't iterate,
Why in React it is loop the elements
The map method does iterate over an array in Javascript. It just also happens to return a new array, whose elements are built using a callback function passed in to map which acts on each element of the original array.
For example:
let arr = [1, 2, 3, 4]
console.log(arr.map(num => num + 1))
===> [2, 3, 4, 5]
It works exactly like forEach, but instead of simply iterating, it returns a new array.
You can also use map to just make a shallow copy of the array:
let arr = [1, 2, 3, 4]
let arrCopy = arr.map(num => num)
console.log(arrCopy)
===> [1, 2, 3, 4]
Hence why it's easy to build out an array of elements using map in React:
let names = ["Mark", "Kelly", "Mike"]
return (
<ol>
{names.map(name => {
return (
<li>{name}</li>
)})}
</ol>
)

Convert 2D nested array into 1D array in JavaScript?

Given a 2D array as shown in the example, how to manage to combine the string digits into one.
ex: Array2 = [[1,2,3],[4,5,6],[7,8,9]];
required sol:
Array1 = [123, 245, 789];
You can deconstruct your task into two separate problems, that we will solve in turn.
We need to take an array of numbers (e.g. [1, 2 ,3]) and join them together into a string (e.g. '123').
There is, in fact, a dedicated function for this in JavaScript - the join() function:
[1, 2, 3].join(''); // '123'
We need to perform the previous function on each object in an array, returning an array of the transformed objects.
JavaScript again has you covered, this time with the map() function:
[a, b, c].map((element) => foo(element)); // [foo(a), foo(b), foo(c)]
All we have to do now is join these too together, so that the operation we perform on each element of the parent array, is to join all of the child elements together:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]].map((array) => array.join('')); // ['123', '456', '789']
function foo(arr){
let toReturn = [];
for(let i = 0;i < arr.length;i++){
toReturn.push(arr[i].join(""));
}
return(toReturn);
}
console.log(foo([[1,2,3],[4,5,6],[7,8,9]]));
You can use reduce to aggregate your data combined with .join('') to get all element items of each array item into a single value like below:
const data = [[1,2,3],[4,5,6],[7,8,9]];
const result = data.reduce((acc, curr) => {
acc.push(curr.join(''));
return acc;
}, []);
console.log(result);
Return all files as a 1D array from given path
const fetchAllFilesFromGivenFolder = (fullPath) => {
let files = [];
fs.readdirSync(fullPath).forEach(file => {
const absolutePath = path.join(fullPath, file);
if (fs.statSync(absolutePath).isDirectory()) {
const filesFromNestedFolder = fetchAllFilesFromGivenFolder(absolutePath);
filesFromNestedFolder.forEach(file => {
files.push(file);
})
}
else return files.push(absolutePath);
});
return files
}

How to know if an array is single dimension or multiple dimension?

I need your help arround array in JS.
I have a function where i need to check if the array passed in argument is one dimension or 2 dimension
let's say :
function test(array){
if(array is single dimension{
console.log("Single dimension");
}else{
console.log("2Dimension");
and the following should display :
test([1,2,3]); // Should log "Single dimension"
test([[1,2,3],[1,2,3]]); // Should log "2Dimension"
Any help will be really nice! Thank you!
How to know if an array is single dimension or multiple dimension?
JavaScript doesn't have multi-dimensional arrays; it has arrays of arrays. There's a subtle difference between those two things. Even more, a JavaScript can have entries that are arrays and other entries that aren't arrays, making it only partially "multi-dimensional."
If you need to know that an array doesn't contain any arrays (e.g., is one-dimensional), the only way is to check every entry in it to see if that entry is an array:
if (theArray.every(entry => !Array.isArray(entry)) {
// One dimensional
} else {
// Has at least one entry that is an array
}
Here's an example of an array that only has some entries that are arrays and others that aren't:
const a = [1, 2, ["a", "b"], 3];
console.log(a.length); // 4, not 5
console.log(Array.isArray(a[0])); // false
console.log(Array.isArray(a[2])); // true
You could take a recursive approach and check the first element for nested arrays.
function getDimension([array]) {
return 1 + (Array.isArray(array) && getDimension(array));
}
console.log(getDimension([1, 2, 3]));
console.log(getDimension([[1, 2, 3], [1, 2, 3]]));
Related to this one
Get array's depth in JavaScript
You can use function like this one :
function getArrayDepth(value) {
return Array.isArray(value) ?
1 + Math.max(...value.map(getArrayDepth)) :
0;
}
Then simply
const testArray = [1,2,3];
if (getArrayDepth(testArray) > 1){
console.log('One array');
}else{
console.log('Array in array')
}
It can be checked like that:
const arr = [1, 2, 3];
const multiDimensional = [
[1,2,3],
[1,2,3]
];
const isMultiDimensional = (arr) => {
const result = arr.reduce((a, c) => {
if (c.constructor === Array)
a = true;
return a;
}, false)
return result;
}
console.log(isMultiDimensional ([1, 2, 3]));
console.log(isMultiDimensional ([[1, 2, 3], [1, 2, 3]]));

Does JS support sorting with a key function, rather than a comparator?

JavaScript's array.sort method takes an optional compare function as argument, which takes two arguments and decides which one of them is smaller than the other.
However, sometimes it would be more convenient to customize the sort order with a key function, which is a function that takes one value as an argument and assigns it a sort key. For example:
function keyFunc(value){
return Math.abs(value);
}
myArr = [1, 3, -2];
myArr.sort(keyFunc);
// the result should be [1, -2, 3]
Does JavaScript have support for this, or is there no way around writing a full-blown comparison function?
There's no support for exactly what you describe, but it's quite trivial to write a standard .sort function that achieves the same thing, with minimal code - just return the difference between calling keyFunc on the two arguments to sort:
function keyFunc(value){
// complicated custom logic here, if desired
return Math.abs(value);
}
myArr = [1, 3, -2];
myArr.sort((a, b) => keyFunc(a) - keyFunc(b));
console.log(myArr);
// the result should be [1, -2, 3]
If the key function is complicated and you don't want to run it more than necessary, then it would be pretty simple to create a lookup table for each input, accessing the lookup table if keyFunc has been called with that value before:
const keyValues = new Map();
function keyFunc(value){
const previous = keyValues.get(value);
if (previous !== undefined) return previous
console.log('running expensive operations for ' + value);
// complicated custom logic here, if desired
const result = Math.abs(value);
keyValues.set(value, result);
return result;
}
myArr = [1, 3, -2];
myArr.sort((a, b) => keyFunc(a) - keyFunc(b));
console.log(myArr);
// the result should be [1, -2, 3]
As stated already you have to write that functionality yourself or extend the current array sort method etc.
Another approach is if you ware using lodash and its orderBy method ... then this becomes:
myArr=[1, 3, -2];
const result = _.orderBy(myArr, Math.abs)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
You could use a closure over the wanted function.
const
keyFunc = value => Math.abs(value),
sortBy = fn => (a, b) => fn(a) - fn(b),
array = [1, 3, -2];
array.sort(sortBy(keyFunc));
console.log(array); // [1, -2, 3]
You can easily subtract the "keys" from the two elements:
myArr.sort((a, b) => keyFunc(a) - keyFunc(b));
You could also monkey patch sort:
{
const { sort } = Array.prototype;
Array.prototype.sort = function(sorter) {
if(sorter.length === 2) {
sort.call(this, sorter);
} else {
sort.call(this, (a, b) => sorter(a) - sorter(b));
}
};
}
So then:
myArr.sort(keyFunc);
works.

why are there different arguments in this javascript function

I saw this function , though it works fine but I am bit puzzled about the function expressions. Here is the code
mapForEach(arr, fn) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(fn(arr[i]))
}
return newArr;
}
can anybody explain to nme what this rather complicated code is actually doing?
Lets say you have var array = [1, 2, 3, 5]; and then run var array2 = mapForEach(array, function(i) { return i * 2; })
array2 would then contain [2, 4, 6, 10].
So it returns a new array where you have the ability to modify each record with a function
mapForEach enumerates an array and calls a supplied function on each element.
example:
var a = [1, 2, 3];
console.log(mapForEach(a, (x) => x * 2));
would create a new array with the values (and output to console):
[2, 4, 6]
Basically it is an implementation of javascript native array function map, which creates a new array with the results of calling a provided function on every element in this array.
More info about mentioned function you can find here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Categories