0

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?

asked Jan 4, 2021 at 7:24

4 Answers 4

3

In ES6 you can try this:

let output = attributeSet.sort((a, b) => a.id - b.id).map(i => `${i.id}-${i.value}`).join(' | ');
answered Jan 4, 2021 at 7:28
Sign up to request clarification or add additional context in comments.

2 Comments

this doesn't sort according to the id. compareFunction needs two parameters - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
can you try to check with re-order your attributeSet @VishalKumar ?
3

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

Comments

0

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

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.