I have javascript array like this
let attributeSet = [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND",
}
]
The format should be in id-value pair. Also the order of id should be in increasing order. Like this
output = 3-1 TB | 4-5 inch | 5-3D Nand
Can anyone help?
4 Answers 4
In ES6 you can try this:
let output = attributeSet.sort((a, b) => a.id - b.id).map(i => `${i.id}-${i.value}`).join(' | ');
Sign up to request clarification or add additional context in comments.
2 Comments
topdev87
this doesn't sort according to the
id. compareFunction needs two parameters - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… topdev87
can you try to check with re-order your attributeSet @VishalKumar ?
Sort array according to id using Array.sort() and join them using Array.join()
const attributeSet = [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND",
}
]
attributeSet.sort((a, b) => a.id - b.id);
const output = attributeSet.map(item => item.id + '-' + item.value).join(" | ")
console.log(output);
answered Jan 4, 2021 at 7:26
topdev87
8,7913 gold badges11 silver badges33 bronze badges
Comments
You can first sort the array by id and then iterate and create new array from that sorted array,
attributeSet = [
{
"name" : "Capacity",
"value" : "1 TB",
"id" : 3
},
{
"name" : "Form Factor",
"value" : "5 inch",
"id" : 4
},
{
"id" : 5,
"name" : "Memory Components",
"value" : "3D NAND",
}
]
attributeSet.sort((a,b) => parseInt(a.id) - parseInt(b.id));
let res = attributeSet.map(item => {
return item.id+'-'+item.value;
})
console.log(res.join(' | '));
answered Jan 4, 2021 at 7:28
Md Sabbir Alam
5,0643 gold badges19 silver badges32 bronze badges
Comments
Use reduce and template string to build the desired string of id-value pairs
const getString = (arr) =>
arr
.sort((a, b) => a.id - b.id)
.reduce((acc, { id, value }, i) => `${acc}${i ? " | " : ""}${id}-${value}`, '');
let attributeSet = [
{
name: "Capacity",
value: "1 TB",
id: 3,
},
{
name: "Form Factor",
value: "5 inch",
id: 4,
},
{
id: 5,
name: "Memory Components",
value: "3D NAND",
},
];
console.log(getString(attributeSet));
answered Jan 4, 2021 at 8:20
Siva Kondapi Venkata
11.1k2 gold badges20 silver badges32 bronze badges
Comments
lang-js