Merge multiple arrays in object [duplicate] - javascript

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)

Related

How to remove dublicate values from array of objects using javaScript? [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 1 year ago.
I have this array of objects, my aim is to remove dublicate values from values array, I want the result to be [{name:'test1', values:['35,5', '35,2','35,3']}, {name:'test2', values:['33,2', '34,3', '32,5']}]
I have tried following solution but it does not works, Do you have any suggestions? Thanks in advance
let arr = [{name:'test1', values:['35,5', '35,2', '35,2', '35,3', '35,5']},
{name:'test2', values:['35,1', '35,1', '33,2', '34,3', '32,5']}]
let uniqueArray = arr.values.filter(function(item, pos) {
return arr.values.indexOf(item.values) == pos;
})
console.log(uniqueArray)
}
}
You can easily remove duplicates from an Array by creating a new Set based off it.
Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection
If you want the result in an array, just use spread syntax for that, for example:
let arr = [{
name: 'test1',
values: ['35,5', '35,2', '35,2', '35,3', '35,5']
},
{
name: 'test2',
values: ['35,1', '35,1', '33,2', '34,3', '32,5']
}
];
const uniqueArr = arr.reduce((accum, el) => {
// Copy all the original object properties to a new object
const obj = {
...el
};
// Remove the duplicates from values by creating a Set structure
// and then spread that back into an empty array
obj.values = [...new Set(obj.values)];
accum.push(obj);
return accum;
}, []);
uniqueArr.forEach(el => console.dir(el));

How to extract object keys [duplicate]

This question already has answers here:
Get array of object's keys
(8 answers)
Closed 2 years ago.
I have this following object:
{
12232: [],
34232: [],
23435: []
}
I want to extract the keys from this object to show them as labels in my React frontend. How can I accomplish this?
The method Object.keys() allows you to loop over the keys of an object.
You should be able to use it in order to get what you want.
See here
Use JS built-in Object.keys() for that.
const myObject = {
12232: [],
34232: [],
23435: []
};
const keys = Object.keys(myObject);
keys.forEach(key => {
console.log(key);
});
You can always use
obj = { abc: "1", def: "2" }
console.log(Object.keys(obj))
It will log ["abc", "def"]. Then you can map through this array and display the values as required.
Ref
You could use Object.keys to extract the keys out of your object.
You could check the docs of Object.keys here
const obj = {
12232 : [],
34232 : [],
23435: []
}
Object.keys(obj); // returns ['12232', '34232', '23435'];

How to create a prefilled array of defined length? [duplicate]

This question already has answers here:
Strange behavior of an array filled by Array.prototype.fill()
(9 answers)
Closed 3 years ago.
I am trying to create an array which has a defined length and fill it with empty arrays. I've tried using all possibilities given by #stpoa's answer here but my array does not behave correctly.
Given the code (I simplified it for the sake of example):
const tasksArray = Array(3).fill([])
const tasksArray2 = [[], [], []]
const tasks = ['task1', 'task2']
const fillWithData = (array) => {
tasks.forEach(task => {
array[0].push(task)
})
}
Gives me an incorrect output for tasksArray and a obviously a correct one for tasksArray2 which is hardcoded
fillWithData(tasksArray) // [['task1', 'task2'], ['task1', 'task2'], ['task1', 'task2']] => not OK, duplicates values!
fillWithData(tasksArray2) // [['task1', 'task2'], [], []] => that's OK
In taskArray, the [] you are using is passed as a reference, and the elements in taskArray all reference the same array.
In taskArray2, you have three separate empty arrays, [], each with their own reference. Therefore you do not get duplicated values.
If you wish to create an array of empty arrays programmatically, use Array.from -
const fillEmptyArrays = (count) =>
Array.from(Array(count), _ => [])
const tasks =
fillEmptyArrays(3)
console.log(tasks)
// [ [], [], [] ]
And please don't include type names like Array in your variable names tasksArray; just name it tasks. JavaScript is a dynamically-typed language and this kind of thinking hurts you in the long run.
You need to get independent object references inside of the array, instead of having literally the constant value.
By taking Array.from with an object with a length property and the build in mapping function, you could get an array of independent arrays.
const tasksArray = Array.from({ length: 3 }, _ => [])
const tasks = ['task1', 'task2']
const fillWithData = (array) => {
tasks.forEach(task => {
array[0].push(task)
})
};
fillWithData(tasksArray);
console.log(tasksArray);
fill puts the value you pass it at each index of the array.
So tasksArray has three references to the same array, while tasksArray2 has a reference to each of three different arrays.
If you want to put three different arrays in there, then you need to explicitly create three arrays.
You could approach it with a counter:
const tasksArray2 = [];
let count = 3;
while (count--) {
tasksArray2.push([]);
}

Array.reduce() on an array of objects -- getting back strings of single letters

I'm working to understand Array.reduce() in JavaScript. I have an array of objects that I'm trying to apply .reduce() to, but I'm getting back an array of single letter strings.
Goal:
["Stuff", "necklace", "ring", "bracelet"]
Current Array of Objects
const productArray =
[
{
id: 1,
productTitle: "Necklace"
},
{
id: 2,
productTitle: "Ring"
},
{
id: 3,
productTitle: "Bracelet"
}
]
Function call
const newStuff = productArray.reduce(function(a, currentValue) {
return [...a, ...currentValue.productTitle];
}, ["Stuff"])
Actual result:
What do I need to do to specify that I don't want "productTitle" broken down into single-letter strings? I have been looking for resources regarding .reduce() on an array of objects but I haven't found anything very helpful. Any pointers?
To concatenate an array and value when using spread to create a new array, you spread the previous array to the new array, and add the new item without spreading it.
const productArray = [{"id":1,"productTitle":"Necklace"},{"id":2,"productTitle":"Ring"},{"id":3,"productTitle":"Bracelet"}];
const newStuff = productArray.reduce((a, currentValue) =>
[...a, currentValue.productTitle], []);
console.log(newStuff);
In this case, it's better to use Array.map():
const productArray = [{"id":1,"productTitle":"Necklace"},{"id":2,"productTitle":"Ring"},{"id":3,"productTitle":"Bracelet"}];
const newStuff = productArray.map((currentValue) => currentValue.productTitle);
console.log(newStuff);
Do not spread the title, pass it as it is:
const newStuff = productArray.reduce(function(a, currentValue) {
return [...a, currentValue.productTitle];
}, ["Stuff"]);
...currentValue.productTitle spreads into an array of individual letters, you only want to spread a variable, the aggregate here.
Basically a string is iterable, because the iterator is implemented and returns an array of single characters, if using spread syntax ....
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
console.log([...'foo']);
Other answers have pointed out why your code is wrong. But I do want to also note that what you're doing is already covered by Array.prototype.concat:
const productArray = [{"id":1,"productTitle":"Necklace"},{"id":2,"productTitle":"Ring"},{"id":3,"productTitle":"Bracelet"}];
const newStuff = productArray.reduce((a, val) => a.concat(val.productTitle), ['Struff']);
console.log(newStuff);
(And of course, as another answer has mentioned, this sounds more like a use for map than reduce, which might not matter since you're using this to learn reduce.)
The use of spread in this case is unnecessary and inefficient as it creates a new accumulator array from the previous one on every iteration. You can remove spread (and fix your issue) and use concat instead to keep it as a one-liner.
However, since you're just adding one new value on each iteration, you should use push. It requires one more line of code but is likely more efficient than using concat.
var productArray = [{id: 1,productTitle: "Necklace"},
{id: 2,productTitle: "Ring"},
{id: 3,productTitle: "Bracelet"}
];
// Using concat
var newStuff = productArray.reduce((acc, value) =>
acc.concat(value.productTitle),
["Stuff"]);
console.log(newStuff);
// Using push
var newStuff = productArray.reduce((acc, value) => {
acc.push(value.productTitle);
return acc;
}, ["Stuff"]);
console.log(newStuff);

How to collect / make new array by existing arrays label wise?

How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console

Categories

Resources