1

I have array object, but i want to create its array: Object format like as:

[
 {"name":"A1","type":"type1"},
 {"name":"A2","type":"type1"},
 {"name":"A3","type":"type1"},
 {"name":"A4","type":"type1"},
 {"name":"B1","type":"type2"},
 {"name":"C1","type":"type3"},
 {"name":"D1","type":"type4"},
 {"name":"D2","type":"type4"}
]

Result format like :

["type1"=>[A1,A2,A3,A4],"type2"=>[B1],"type3"=>[C1],"type3"=>[D1,D2]]

2 Answers 2

1

You could iterate the array with Array#forEach and use an object with the type as keys.

var data = [{ "name": "A1", "type": "type1" }, { "name": "A2", "type": "type1" }, { "name": "A3", "type": "type1" }, { "name": "A4", "type": "type1" }, { "name": "B1", "type": "type2" }, { "name": "C1", "type": "type3" }, { "name": "D1", "type": "type4" }, { "name": "D2", "type": "type4" }],
    grouped = {};

data.forEach(function (a) {
    grouped[a.type] = grouped[a.type] || [];
    grouped[a.type].push(a.name);
});

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

1

You could also do this with a reduce

.reduce((prev, cur) => {
  if (prev.hasOwnProperty(cur.type))
    prev[cur.type].push(cur.name);
  else
    prev[cur.type] = [cur.name];

  return prev;
}, {});

The nice thing about this approach is there is no need for extra variables out of the scope of the reduce, it simply returns your grouped object.

see fiddle

Comments

Your Answer

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.