How can I create keys for an array in Javascript? [duplicate] - javascript

This question already has answers here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Convert array of strings to objects and assign specific key
(1 answer)
Closed 3 years ago.
I would like to know how can I create keys for an array of values in javascript like this?
const array = ["NodeJs", "Javascript", "React"]
and transform it like this
const array = [{"name": "NodeJs"}, {"name": "Javascript"}, {"name": "React"}]

Using Array.prototype.map:
const arr = ["NodeJs", "Javascript", "React"];
const newArr = arr.map(name => ({name})); // or arr.map(item => ({name: item}))
console.log(newArr);

You can also do it using Array.from(iterable, mappingFunction) which will return a new array with objects {name: name}:
const array = ["NodeJs", "Javascript", "React"];
const mapArray = Array.from(array, (name) => ({name}));
console.log(mapArray);

Related

How do you group an array via JavaScript [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 4 months ago.
How do I group the array via javascript to just
Vehicles
Food
I can't figure it out via "reduce" since the array has no "key" to specify.
Thank you
const group1 = arr.filter(item => item === 'Vehicles');
const group2 = arr.filter(item => item === 'Food');
Or if you want a general solution:
let groups = {};
for (const item of arr) {
if (!groups[item]) groups[item] = [];
groups[item].push(item);
}
I think I don't get your question completely, but if you are trying to remove duplicates, this could be an option
const originalArray = ["vehicle", "food", "vehicle", "food", "vehicle", "food"];
const noDuplicates = new Set(originalArray);
console.log(Array.from(noDuplicates));

create arrays from array containing similar path items [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Closed 7 months ago.
I have array like this
Var arr =[
["ali", "classroom1"],
["john", "classroom1"],
["Doe", "classroom1"],
["ahmed", "classroom2"],
["Mo", "classroom2"],
["Wael", "classroom3"]
]
Now I want to create arrays or slit it to get array for classroom1 and different array for classroom2 .....
I used splice and map but it seems they're not used for this
Consider something like this:
let arr =[
["ali", "classroom1"],
["john", "classroom1"],
["Doe", "classroom1"],
["ahmed", "classroom2"],
["Mo", "classroom2"],
["Wael", "classroom3"]
];
let classrooms = new Map();
for (let item of arr) {
const [name, classroom] = item;
if (!classrooms.has(classroom)) {
classrooms.set(classroom, []);
}
classrooms.get(classroom).push(name);
}
console.log(classrooms);

javascript: create dictionary from array of key-values objects [duplicate]

This question already has answers here:
How to convert an array of objects to object with key value pairs
(6 answers)
Merge multiple objects inside the same array into one object [duplicate]
(2 answers)
How to concatenate properties from multiple JavaScript objects
(14 answers)
Closed 1 year ago.
I have an array of objects.
const ar = [ {0 : "A"}, {1 : "B"}];
I want to create an dictionary from it
const di = {0 : "A", 1 : "B"};
I am a little struggling with this conversion. How it is possible to do it using map or reduce?
const di = ar.map( ob => (???) }
A simple reduce can be used to merge all objects. Be aware that the keys need to be unique otherwise you will overwrite them.
The merging is done with the spread syntax
const ar = [{0 : "A"}, {1 : "B"}];
const di = ar.reduce((acc, obj) => ({...acc, ...obj}));
console.log(di);
Another simple approach is the use of Object.assign
const ar = [{0 : "A"}, {1 : "B"}];
const di = Object.assign({}, ...ar);
console.log(di);
You should use reduce here instead of map. map will give you an array of objects but what you need is an object will all keys. So reduce is the best tool for it.
Main difference between map and reduce
const ar = [{ 0: "A" }, { 1: "B" }];
const di = { 0: "A", 1: "B" };
const result = ar.reduce((acc, curr) => {
Object.keys(curr).forEach((k) => (acc[k] = curr[k]));
return acc;
}, {});
console.log(result);

Javascript to Group Array of Object into combination of two values [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Create Multilevel groups from an Array of Objects
(2 answers)
Closed 4 years ago.
var data=[
{custType:1,code:'savings',efDate:'2/3/19',exDate'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
];
expected results
var modifiedData=[
[
savings=[ {custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:1,code:'savings',efDate:'2/3/19',exDate:'2/3/19'}
],
current=[ {custType:1,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
],
[
savings=[ {custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'},
{custType:2,code:'savings',efDate:'2/3/19',exDate:'2/3/19'} ],
current=[ {custType:2,code:'current',efDate:'2/3/19',exDate:'2/3/19'} ]
]
];
as i am trying to find a group with (custType and code), i am not able to generate the expected result. Which method i should use here? can i use reduce or groupBy. I am confused about it.
You could build up a nested hashtable:
const hash = {};
for(const value of data) {
const group = hash[value.custType] || (hash[value.custType] = {});
const group2 = group[value.code] || (group[value.code] = []);
group2.push(value);
}
const result = Object.values(hash).map(Object.values);

Merge multiple arrays in object [duplicate]

This question already has answers here:
Concatenate Object values
(4 answers)
Closed 7 months ago.
I'm looking at an efficient way to merge multiple array props in an object.
The object, can have multiple array properties in there :
{
"col0Codes": [
"ABC",
"XYZ",
"UYA",
"ZZA",
"AAW",
"MYP"
],
"col1Codes": [
"CNA",
"ZYA",
"OIA",
"POQ",
"LMO",
"OPI"
],
"col2Codes": [
"CNA",
"ZYA",
"OIA",
"POQ",
"LMO",
"OPI"
],
"col3Codes": [
"..."
],
"col4Codes": [
"..."
],
...
}
Result: All the codes in a single array
["ABC","XYZ","UYA","ZZA","AAW","MYP","CNA","ZYA","OIA","POQ","LMO","OPI",....]
I've tried using concat but this creates a new array every single time and overwrites the previous one, I feel this is not fast and memory efficient.
let colCodes = []
for (let i in data) {
colCodes = colCodes .concat(i)
}
console.log(activityCodes)
I've tried using push, but for some reason it does not merge all the entries into one single array but creates a single array with number of props in the object as shown below
let colCodes = []
for (let i in data) {
colCodes.push(i)
}
console.log(colCodes)
[Array(6), Array(5), ....]
Is there anyway I can achieve this using reduce, if that is what'll be fast and mem efficient ?
You can get an array of arrays using Object.values(), and then flatten them to a single array using Array.flat():
const data = {"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
const result = Object.values(data).flat();
console.log(result);
Old answer:
You can get the Object.values(), then merge by spreading into Array.concat():
const data = {"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
const result = [].concat(...Object.values(data));
console.log(result);
You could also simply Array.reduce the Object.values with ES6 spread:
const input={"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
console.log(Object.values(input).reduce((r,c) => [...r, ...c]))
One way would be to use Array.prototype.flat, and call it on the values of the object:
const input={"col0Codes":["ABC","XYZ","UYA","ZZA","AAW","MYP"],"col1Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"],"col2Codes":["CNA","ZYA","OIA","POQ","LMO","OPI"]};
console.log(
Object.values(input).flat()
);
You can try this
let obj = {"col0Codes": ["ABC","XYZ","UYA","ZZA","AAW","MYP"],
"col1Codes": ["CNA","ZYA","OIA","POQ","LMO","OPI"],
"col2Codes": ["CNA","ZYA","OIA","POQ","LMO","OPI"],
"col3Codes": ["..."],
"col4Codes": ["..."]
}
let op = [];
for(let key in obj){
op.push(...obj[key])
}
console.log(op)

Categories

Resources