3

I am having json array object in my Angular 4 application and where i need to find out unique space type in my JSON array.

Json Array:

[{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Hospital_Lab"}},
{"label":{"Space_Type":"Office_OpenOffice"}},
{"label":{"Space_Type":"Office_PrivateOffice"}},
{"label":{"Space_Type":"Office_PrivateOffice"}},{},
{"label":{"Space_Type":"Office_PrivateOffice"}},
{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Hospital_Lab"}},{"label":{"Space_Type":"Office_OpenOffice"}},{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Office_OpenOffice"}},{}]

I want to remove all the duplicate space type .Can anyone tell me how i can get. I want the result :

[{Idx:0,Label:"Office_PrivateOffice"},{Idx:1,Label:"Office_OpenOffice"}]
1
  • this is pure javascript data manipulation. you can write a function to do that or you can use lodash or underscore Commented Oct 9, 2017 at 18:49

2 Answers 2

6

You can use lodash method _.uniqWith

var jsonarray =  [{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Hospital_Lab"}},
{"label":{"Space_Type":"Office_OpenOffice"}},
{"label":{"Space_Type":"Office_PrivateOffice"}},
{"label":{"Space_Type":"Office_PrivateOffice"}},{},
{"label":{"Space_Type":"Office_PrivateOffice"}},
{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Hospital_Lab"}},{"label":{"Space_Type":"Office_OpenOffice"}},{"label":{"Space_Type":"Office_PrivateOffice"}},{"label":{"Space_Type":"Office_OpenOffice"}},{}];


var filtered =  _.uniqWith(jsonarray, _.isEqual);

console.log(filtered);
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>

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

Comments

1

The lodash method _.uniqBy(root, 'duplicateElement'); can also be used. The advantage of using this method is that you can tell lodash which element you would like to remove duplicate of.

var newJsonFile = _.uniqBy(label, 'Space_Type'); 
console.log(newJsonFile);

In Angular, you would need to download package lodash

npm install lodash

Then import it

import * as _ from 'lodash';    

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.