Combine object array if same key value in javascript [duplicate] - javascript

This question already has answers here:
Merge specific properties of objects together with JavaScript
(3 answers)
Closed 3 years ago.
I would like to know how to combine array values if same id in javascript.
I tried below code
let result = this.getData(obj);
function getData(obj) {
return obj.map(e=>({procode: e.prcode, id: e.id});
}
var obj= [
{
id: "1",
prcode: "dessert"
},{
id: "1",
prcode: "snacks"
}, {
id: "2",
prcode: "cafe"
}, {
id: "4",
prcode: "all"
}
]
Expected Output:
result = [
{id: "1", prcode: "dessert,snacks"},
{id: "2", prcode: "cafe"},
{id: "4", prcode: "all"}
]

You can use reduce alongside Object.values():
var obj = [
{ id: "1", prcode: "dessert" },
{ id: "1", prcode: "snacks" },
{ id: "2", prcode: "cafe" },
{ id: "4", prcode: "all" }
]
const out = obj.reduce((a, v) => {
if(a[v.id]) {
a[v.id].prcode = [a[v.id].prcode, v.prcode].join(',')
} else {
a[v.id] = v
}
return a
}, {})
console.log(Object.values(out))

Related

filter object value using node js

Is there any way i can filter values which are present inside Object
[
{
id: "1",
name:"animal_image.jpg"
},
{
id: "2",
name:"fish_image.jpg"
},
{
id: "3",
name:"animal_doc.txt"
},{
id: "4",
name:"fish_doc.txt"
},
{
id: "4",
name:"flower_petals.jpg"
},
{
id: "5",
name:"plant_roots.jpg"
},
{
id: "6",
name:"human_image.jpg"
},
]
i want to filter all the name which contain_image.jpg so output look like this
output=
[ "human_image.jpg",
"anima_image.jpg",
"fish_image.jpg"
]
In this code snippet filtredData is an array of objects where the name includes _image.jpg and output is just an array of names containing _image.jpg
const data = [
{
id: "1",
name: "animal_image.jpg"
},
{
id: "2",
name: "fish_image.jpg"
},
{
id: "3",
name: "animal_doc.txt"
}, {
id: "4",
name: "fish_doc.txt"
},
{
id: "4",
name: "flower_petals.jpg"
},
{
id: "5",
name: "plant_roots.jpg"
},
{
id: "6",
name: "human_image.jpg"
},
]
const filtredData = data.filter(el => el.name.includes("_image.jpg"));
console.log(filtredData);
const output = filtredData.map(el => el.name);
console.log(output);
filter & map
const output = arr
.filter(x => x.name.endsWith('_image.jpg'))
.map(x => x.name);

filtered by name using node js

Is there any way i can filter files with given extension and then further filter them
for eg: I have .txt extension and i want to get all my .txt from an array
file=
[ "animal_bio.txt",
"xray.pdf",
"fish_bio.txt",
"mammal_doc.txt",
"human_bio.txt",
"machine.jpg"
]
filtered output contain all .txt extension and further it should contain all the files which have _bio.txt name in it.
so output look like
futherFile=
[ "human_bio.txt",
"fish_bio.txt",
"animal_bio.txt"
]
You can use String.protytype.endsWith function to compare the strings with your extension
const file =
[ "animal_bio.txt",
"xray.pdf",
"fish_bio.txt",
"mammal_doc.txt",
"human_bio.txt",
"machine.jpg"
]
result = file.filter((fileName) => fileName.endsWith("_bio.txt"));
console.log(result)
You can use the Array.filter method and use the String.endsWith method to filter. An example -
// List of files
file = ["animal_bio.txt",
"xray.pdf",
"fish_bio.txt",
"mammal_doc.txt",
"human_bio.txt",
"machine.jpg"
]
// Filtering by extension
file.filter(x => x.endsWith(".txt"));
Hope it helped :)
You can easily achieve this result using reduce and match
When matching for the doc or bio, You can even restrict more to get the string only if _doc.txt is at end of the string using Regular expression /_bio.txt$/
const arr = [
{
id: "1",
name: "animal_bio.txt",
},
{
id: "2",
name: "xray.pdf",
},
{
id: "3",
name: "animal_doc.txt",
},
{
id: "4",
name: "fish_doc.txt",
},
{
id: "5",
name: "flower_petals.jpg",
},
{
id: "5",
name: "plant_roots.jpg",
},
{
id: "6",
name: "human_image.jpg",
},
{
id: "7",
name: "human_bio.txt",
},
{
id: "8",
name: "mammal_doc.txt",
},
];
const result = arr.reduce((acc, { name }) => {
if (name.match(/\.txt$/)) {
if (name.match(/_bio/)) {
acc[0].push(name);
} else {
acc[1].push(name);
}
}
return acc;
},
[[], []]
);
console.log(result);
Then you can get the element containing doc and bio using array destructuring as
const [bioArr, docArr] = result;
console.log(bioArr);
console.log(docArr);
const arr = [
{
id: "1",
name: "animal_bio.txt",
},
{
id: "2",
name: "xray.pdf",
},
{
id: "3",
name: "animal_doc.txt",
},
{
id: "4",
name: "fish_doc.txt",
},
{
id: "5",
name: "flower_petals.jpg",
},
{
id: "5",
name: "plant_roots.jpg",
},
{
id: "6",
name: "human_image.jpg",
},
{
id: "7",
name: "human_bio.txt",
},
{
id: "8",
name: "mammal_doc.txt",
},
];
const result = arr.reduce(
(acc, { name }) => {
if (name.match(/\.txt$/)) {
if (name.match(/_bio/)) {
acc[0].push(name);
} else {
acc[1].push(name);
}
}
return acc;
},
[[], []]
);
const [bioArr, docArr] = result;
console.log(bioArr);
console.log(docArr);
you can use filter function from ES6 like:
const txtFile = file.filter((item) => (item.split('_'))[1] === 'bio.txt')

TypeError: Cannot read property 'id' of undefined when map over two arrays [duplicate]

This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 2 years ago.
i'm trying to load 4 random cities every time the main page loads using useEffect() hook and i am subtracting the items i already found to avoid duplications so i wrote this function :
const cities = [
{ id: "0", name: "New York" },
{ id: "1", name: "California" },
{ id: "2", name: "Tokyo" },
{ id: "3", name: "Paris" },
{ id: "4", name: "Oran" },
{ id: "5", name: "roma" },
{ id: "6", name: "dubai" },
{ id: "7", name: "madrid" },
{ id: "8", name: "beijing" },
{ id: "9", name: "montreal" }
];
const randomCitiesLoader = () => {
let randomCities = [];
randomCities.push(cities[Math.floor(Math.random() * cities.length - 1)]);
for (let i = 0; i < 3; i++) {
let queryCities = cities.filter(city => {
return !randomCities.find(item => {
return item.id === city.id;
});
});
randomCities.push(
queryCities[Math.floor(Math.random() * queryCities.length - 1)]
);
}
return randomCities;
};
but i'm getting this error :
can someone please help
Math.floor(Math.random()*cities.length-1) can be -1 so you can push undefined to resulting array because cities[-1] is undefined.
You best option would be to use array[Math.floor(Math.random()*array.length)] to pick random element from array.

Restructuring Javascript Arrays

EDIT: Thanks for the replies!
I am kind of new to working with Javascript (sorry for probably the bad code). I've mainly only worked with HTML and CSS. I have been trying to experiment with Javascript, but I've been stuck on this forever. The outcome is not what I want it to be.
My code:
I want to make the array easier to use, by putting the values under the same category, but my code's output is not exactly what I want it to be like.
var data = {
idName: "idName",
valueRanges: [{
range: "range",
majorDimension: "ROWS",
values: [
[
"ID",
"Category",
"Name"
],
[
"1",
"Category1",
"Name1"
],
[
"2",
"Category1",
"Name2"
],
[
"3",
"Category2",
"Name3"
],
[
"4",
"Category1",
"Name4"
]
]
}]
}
var rows = [];
let batchRowValues = data.valueRanges[0].values
for (let i = 1; i < batchRowValues.length; i++) {
let rowObject = {};
for (let j = 0; j < batchRowValues[i].length; j++) {
rowObject[batchRowValues[0][j]] = batchRowValues[i][j];
}
rows.push(rowObject);
}
var newArray = rows.reduce(function(acc, curr) {
var findIfNameExist = acc.findIndex(function(item) {
return item.Category === curr.Category;
})
if (findIfNameExist === -1) {
let obj = {
'Category': curr.Category,
'value': [curr]
}
acc.push(obj)
} else {
acc[findIfNameExist].value.push(curr)
}
return acc;
}, []);
console.log('------------')
console.log('input: ' + JSON.stringify(data, null, 2))
console.log('------------')
console.log('output: ' + JSON.stringify(newArray, null, 2))
My code's output:
[
{
Category: "Category1",
value: [
{
Category: "Category1",
ID: "1",
Name: "Name1"
},
{
Category: "Category1",
ID: "2",
Name: "Name2"
},
{
Category: "Category1",
ID: "4",
Name: "Name4"
}
]
},
{
Category: "Category2",
value: [
{
Category: "Category2",
ID: "3",
Name: "Name3"
}
]
}
]
How I want it to look:
[
{
Category: "Category1",
values: [
{
ID: "1",
Name: "Name1"
},
{
ID: "2",
Name: "Name2"
},
{
ID: "4",
Name: "Name4"
}
]
},
{
Category: "Category2",
values: [
{
ID: "3",
Name: "Name3"
},
]
},
]
I want to learn! I appreciate any help.
You can use reduce.
Here idea is
Create a object and use category as key
If a category is already found than push the desired object in it's value property. if not than we create a new one with suitable data.
I am using object here instead of array directly is because i can directly access element using key where as in array i need to loop through each time and check existence of value
var data = {idName: "idName",valueRanges: [{range: "range",majorDimension: "ROWS",values: [["ID","Category","Name"],["1","Category1","Name1"],["2","Category1","Name2"],["3","Category2","Name3"],["4","Category1","Name4"]]}]}
var rows = [];
let batchRowValues = data.valueRanges[0].values.slice(1,)
let op = batchRowValues.reduce((op,[ID,Category,Name]) => {
if( op[Category] ){
op[Category].value.push({ID,Name})
} else {
op[Category] = {
Category,
value: [{ID,Name}]
}
}
return op
},{})
console.log(Object.values(op))
Try (t={}, result in r)
data.valueRanges[0].values.slice(1).map( ([i,c,n])=>
(t[c]=t[c]||{Category:c,values:[]}, t[c].values.push({ID:i, Name:n})) );
let r= Object.values(t);
var data =
{
idName: "idName",
valueRanges: [
{
range: "range",
majorDimension: "ROWS",
values: [
[
"ID",
"Category",
"Name"
],
[
"1",
"Category1",
"Name1"
],
[
"2",
"Category1",
"Name2"
],
[
"3",
"Category2",
"Name3"
],
[
"4",
"Category1",
"Name4"
]
]
}
]
}
let t={};
data.valueRanges[0].values.slice(1).map( ([i,c,n])=>
(t[c]=t[c]||{Category:c,values:[]}, t[c].values.push({ID:i, Name:n})) );
let r= Object.values(t);
console.log(r);

How to get distinct properties value from array? [duplicate]

This question already has answers here:
Remove duplicates form an array
(17 answers)
Closed 5 years ago.
I have this array?
var arr = [{id:"1",Name:"Tom"},
{id:"2",Name:"Jon"},
{id:"3",Name:"Tom"},
{id:"4",Name:"Jack"}]
From array above I need to fecth all existing Names distinct.
var result = getNamesDistinct(arr);
The result should contain result is:
["Tom","Jon","Jack"];
My question is how to get all existing Names from arr distinct?
If Set is available, you can simply do
new Set(arr.map(obj => obj.Name))
(pass the set to Array.from if you need an array)
You can do it via Set object
const arr = [
{ id: "1", Name: "Tom" },
{ id: "2", Name: "Jon" },
{ id: "3", Name: "Tom" },
{ id: "4", Name: "Jack" }
];
const uniqueNames = [...new Set(arr.map(item => item.Name))];
console.log(uniqueNames);
Or you can iterate over the array and add condition to get only unique names.
const arr = [
{ id: "1", Name: "Tom" },
{ id: "2", Name: "Jon" },
{ id: "3", Name: "Tom" },
{ id: "4", Name: "Jack" }
];
const uniqueNames = arr.reduce(function(arr, item) {
if(arr.indexOf(item.Name) === -1) {
arr.push(item.Name);
}
return arr;
}, []);
console.log(uniqueNames);
you can try this
var array = [{
id: "1",
Name: "Tom"
}, {
id: "2",
Name: "Jon"
}, {
id: "3",
Name: "Tom"
}, {
id: "4",
Name: "Jack"
}]
function uniqueNames(array) {
var newArray = [];
array.forEach((value, key) => {
newArray.push(value.Name)
});
return newArray
}
var myNewArray = uniqueNames(array)

Categories

Resources