JavaScript Array Map Function not working as expected [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have got an issue with the Array.map function not working as I would expect. I have simplified my example below, I just want to get an understanding of where I am going wrong.
So I have the following code below:
console.log(this.reportTestData)
let data = this.reportTestData.map((row) => {
return [ 1 , 2, 3]
});
console.log(data)
return data
From the first console.log, this.reportTestData is an array containing 92 objects, the content of each object is irrelevant:
So from the code, I would expect the map function to run over the array 92 times, and return a new array ( [1,2,3] ) for each element. Leaving me with an array of 92 elements, which each element is a [1,2,3] array. However that is not what I get.
Instead I am getting an array of 92 elements, but each element is completely empty.
I also tried to return objects from the map function instead:
console.log(this.reportTestData)
let data = this.reportTestData.map((col) => {
return { test : 1 }
});
console.log(data)
return data
However I still get empty objects returned with no properties:
Any help that could be offered would be greatly appreciated, as I cannot see where I am making a mistake.

I tried for 10 items in an array, and as you may see there are 10-pieces of [1,2,3] ... so map function is working fine, as par I can say.
let reportTestData = [1,2,3,4,5,6,7,8,9,10]
console.log(reportTestData)
let data = reportTestData.map((item) => [ 1 , 2, 3]);
console.log(data)
Now trying again with 10-objects in an array:
let reportTestData = [{},{},{},{},{},{},{},{},{},{}]
console.log(reportTestData)
let data = reportTestData.map((item) => [ 1 , 2, 3]);
console.log(data)
Again map function of Arrays works fine, so you need to check what wrong you are doing in your code.

Works for me
const reportTestData = new Array(12).fill(0);
let data1 = reportTestData.map((row) => {
return [ 1 , 2, 3]
});
console.log(data1)
let data2 = reportTestData.map((row) => {
return { test : 1 }
});
console.log(data2)

Related

Can I use an anonymous function with the .map() iterator in javascript? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to get this code to return a new array using .map(). For some reason I cannot figure out how to make the anonymous function work with it. Here is my code. It just returns undefined, smh.
const numbers = [2, 7, 9, 171, 52, 33, 14]
const toSquare = num => num * num
// Write your code here:
function squareNums(numArr) {
numArr.map(num => {
return (num ** 2);
})
};
const numberArray = squareNums(numbers);
console.log(numberArray);
Your code is correct, it's just your squareNums function doesn't return anything. In fact, that means it returns undefined, which is what you see printed in the console.
Return the result of numArr.map instead:
function squareNums(numArr) {
- numArr.map(num => {
+ return numArr.map(num => {
return (num ** 2);
})
};

How to Count Unique Arrays in a Multidimensional Array [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 3 years ago.
Improve this question
I am looking for a way to not only find unique arrays within a multidimensional array, but also count how many times a particular array occurs.
For Example
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
// Code
???
// Results
uniqueArrays === [[1,2], [1,3], [1,4]]
theCount ==== [2, 1, 3]
Edit:
I didn't realize that I had to show my attempts of how I should solve a problem before I asked a question.
I do know how to count the length of an array use the length() method. I do know how to filter unique arrays from a multi-dimensional array. I did not post my attempts using those tools though because those two issues have been solved to death.
You can map each inner array to a stringified version of itself using .map(JSON.stringified). Now, using this new array, you can reduce it to an object which contains each stringified array as a key, and keeps the number of occurrences as its value. While reducing, you can check whether or not the object's key has already been set using a[k] = (a[k] || 0)+1. If it has already been set, it will use the current number stored at the key and increment it by 1, if it hasn't already been set it will set it equal to zero, and then increment it by 1 (which acts as the default value for any new keys (i.e newly seen arrays)).
Lastly, you can get the keys from your object which represent each unique array as strings using Object.keys(), and parse each back into a non-stringified array using JSON.parse. You can get the counts from your array by using Object.values() as this will get all the values (ie: the counters) of your reduced object and put them into an array.
See example below:
const arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
const arr_str = arr.map(JSON.stringify);
const arr_map = arr_str.reduce((a, k) => (a[k] = (a[k] || 0) + 1, a), {});
const uniqueArrays = Array.from(Object.keys(arr_map), JSON.parse);
const theCount = Object.values(arr_map);
console.log(uniqueArrays);
console.log(theCount);
you can use below code
var arr = [[1,2], [1,2], [1,3], [1,4], [1,4], [1,4]];
var uniqueArrays = [];
var theCount = [];
var test = [], obj ={};
arr.forEach(val => {
if(test.indexOf(val.toString()) == -1){
test.push(val.toString());
obj[val.toString()] = 1;
uniqueArrays.push(val);
}else{
obj[val.toString()] += 1;
}
})
theCount = Object.values(obj);
console.log(uniqueArrays);
console.log(theCount);
Hope it will help you.

How can I reverse an array using map? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I get the error that "array" is undefined when running this code. In my solution, I need to use map() to reverse my array.
var names = ["Lars", "Jan", "Peter","Bo", "Frederik","Anna"];
var newArray = array.slice(0).reverse().map(function(name){
return name;
});
console.log(backwards(newArray));
you have to provide the array names instead of using array, which is undefined
var names = ["Lars", "Jan", "Peter", "Bo", "Frederik", "Anna"]
var newArray = names.slice(0).reverse().map(function(name) {
return name;
});
console.log(newArray)
also most of the functions do nothing in this case. You really only need names.reverse() as mentioned in the comment.
If you do want to use map(), it's a bit more complicated, and not the right function to use for reversal.
update
How can I convert it to a function???
well reverse already is a function, but if you want to use map and create a new function using es6 style convention, (const foo = () => {})) you could use map as an iterater, as Nina Scholz did in her answer.
var names = ["Lars", "Jan", "Peter", "Bo", "Frederik", "Anna"]
const backwards = (arr) => arr.map((_, i) => arr[arr.length - i - 1]);
console.log(backwards(names))
console.log(backwards([0, 1, 2]))
You could map the items with a calculated index.
var names = ["Lars", "Jan", "Peter", "Bo", "Frederik", "Anna"],
reversed = names.map((_, i, a) => a[a.length - i - 1]);
console.log(reversed);
Hmm there is no point in using map it can be simply done on this way
var newArray = names.reverse();

javascript, merge two arrays by index [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Here are two arrays:
const a = [1, null, 2, null]
const b = [null, null, 3, 4, null]
Note: The length of a and b is not fixed.
I want elements of b replace elements of a by index if the element is not null.
expect value:
[1, null, 3, 4]
const result = b.map((el, i) => el === null ? a[i] : el);
result.push(...a.slice(b.length));
Just map to a new array.
You can use map() function
var x=b.length+1;
b.concat(a);
var c=b.map(function(el, index) {
if(a[index]!=null && b[index]==null){
return b[index]=a[index];
else{
return b[index]
}
console.log(c.slice(0,x));

Adding a new JSON object in front of JSON array set [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
Playing with nodeJs currently and have been trying to write new data into an existing JSON file, only to have problems with the format as well as getting the right data in. I want to get this new JSON obj to the FIRST of the array list. I did this by grabbing the first index ID, increment it, and tried using unshift() but it isn't adding the way I expected.
JSON file content data.json:
[
{
"id": 3,
"content": "three"
},
{
"id": 2,
"content": "two"
},
{
"id": 1,
"content": "one"
}
]
Code I wrote for new JSON obj I want to add:
var allJSON = fs.readFileSync('data.json');
var allj = JSON.parse(allJSON);
var lastId = parseInt(allj[0].id);
var newData = {
id: ++lastId,
content: "test"
};
var allNewJSON = allj.unshift(JSON.stringify(newData));
// this yields a result of just the number "4" and erased everything else.
Array#unshift does not create and return a new array; instead, it modifies the original array and returns its new length. In your case, this value would be 4. I would suggest ignoring the return value of unshift and simply continuing your code using the allj variable, like so:
var allJSON = fs.readFileSync('data.json');
var allj = JSON.parse(allJSON);
var lastId = parseInt(allj[0].id);
var newData = {
id: ++lastId,
content: "test"
};
allj.unshift(newData);
console.log(allj) // modified as desired!
Edit: As was mentioned in the comments above, you probably don't want to be calling JSON.stringify on the object newData before inserting it into your array. At this point you want to be working with JS objects rather than JSON strings.
Your result is due to the way unshift works.
unshift is a function which returns the length of the updated array.
For example
> const a = [10, 20, 30];
> a.unshift(5);
4
That's right, the call to unshift returns 4, because the updated array has 4 elements.
Let's see the updated value of a:
> a
[5, 10, 20, 30]

Categories

Resources