How can I reverse an array using map? [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 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();

Related

JavaScript Array Map Function not working as expected [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 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)

How to use the reduce operation in javascript? [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 1 year ago.
Improve this question
I am currently trying to simplify the following code written in Javascript
let x = 5;
let y = 10;
let z = 19;
let answer;
arrays = ["x", "y", "z"];
if("x" in arrays){
answer = x;
}
if("x" in arrays && "y" in arrays){
answer = x + y
}
The code will continue on and on for all the possible combinations of x, y and z. What I want to know is how I can simplify the above block of code and achieve the same result.
Thank you.
Instead of individual variables, create an object with your name/value pairs. Then it's trivial to iterate over the names in the array, use them to access the values in the object, and add them together. In fact, this is most naturally expressed as a reduce operation:
let vals = {
x: 5,
y: 10,
z: 19
};
let answer = ["x", "y", "z"].reduce((a, k) => a + vals[k], 0);
console.log(answer);

Add all the elements in an array without using loops [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
How to add elements without using loops and the built-in method of the array like for , foreach etc) and built in methods(like reduce,map...) of array
How can we do the addition?
var arr =[1,2,2,3,4...];
arr length also dynamic.
You can use Spread ... operator like this
var arr1 = [1, 2, 3, 4];
var arr2 = [5,6,7,8];
console.log([...arr1, ...arr2]);
Addition as in sum?
const arr = [1,2,2,3,4];
// normal way
let sum = arr.reduce((a,b) => a+b)
console.log(sum)
// weird way not using loops but still using a built-in method
sum = eval(arr.toString().replace(/,/g,"+"))
console.log(sum)
You can use concat for that whice creates a new array and returns the result so arr1 and arr2 will remain unchanged.
const arr1 = [1, 2];
const arr2 = [3, 4,5,6,7,8];
const combined = arr1.concat(arr2);
console.log(combined);
console.log(arr1);
console.log(arr2);
If you want to mutate the original array you can use push and the spread operator (...):
const a = [1,2]
const b = [3,4,5,6]
a.push(...b)
console.log(a);

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.

create an array of objects from objects javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have this objects from google API, if I console.log(ret) I have this:
{name:x, stars:5},
{name:y, stars:4},
{name:j, stars: 3}
I am getting this result from the following loop:
for (let i = 0; i < fromGoogle.length; i++) {
let ret = fromGoogle[i];
}
I want to create an Array of Objects like:
[{...},{...},{...}]
How do I do it?
Thank you, I am new at JS
If you have, for instance, objects referenced by individual variables:
let a = {name:x, stars:5};
let b = {name:y, stars:4};
let c = {name:j, stars: 3};
you can create an array of them using an array initializer (aka "array literal"):
let array = [a, b, c];
You don't need the individual variables, though, you can do this:
let array = [
{name:x, stars:5},
{name:y, stars:4},
{name:j, stars: 3}
];

Categories

Resources