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?

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(' | ');
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);

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(' | '));

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.