1

I have an object that contains a list of attributes with corresponding attribute values.

Some of the arrays of values have duplicates values that I'd like to remove.

Example

let attributes = [{
  "attribute": "Size",
  "values": ["S", " S", "M", "L", "L"]
},{
  "attribute": "Shape",
  "values": ["Square", "Round", "Square", " Square", " Square"]
}]

let filtered_attributes = attributes.forEach(el => {
  el.map(a => a.values.trim())
  .filter((item, pos, self) => { return self.indexOf(item) === pos })
  .sort();
})

Desired Output

[{
  "attribute": "Size",
  "values": ["L", "M", "S"]
},{
  "attribute": "Shape",
  "values": ["Round", "Square"]
}]

How can I return a list of unique values (those with whitespace first trimmed) for each object in the array?

2 Answers 2

2

You can use Set and spread operator instead of filter:

let attributes = [{
 "attribute": "Size",
  "values": ["S", " S", "M", "L", "L"]
},{
  "attribute": "Shape",
  "values": ["Square", "Round", "Square", " Square", " Square"]
}]

attributes.forEach(el => {
  el.values = [...new Set(el.values.map(a => a.trim()))].sort();
})
console.log(attributes);
Sign up to request clarification or add additional context in comments.

4 Comments

I'm a bit confused as to why filtered_attributes is undefined and we're logging attributes.
forEach only iterates over elements - it doesn't return anything (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…). But inside forEach we change the content for each attribute
If you want filtered_attributes to contain your change you should change it to the following: let filtered_attributes = attributes.map(el => { el.values = [...new Set(el.values.map(a => a.trim()))].sort(); return el })
Awesome. Thank you Alonas :)
0

You can use map plus destructuring to get to the props, then you can filter your values prop from there, trimming each value inside of the filter.

let attributes = [{
  "attribute": "Size",
  "values": ["S", " S", "M", "L", "L"]
},{
  "attribute": "Shape",
  "values": ["Square", "Round", "Square", " Square", " Square"]
}]

// usage example:
let unique = attributes.map(({ attribute, values }) => ({
  attribute, values: values.filter((v, i, s) => s.indexOf(v.trim()) === i) // v, i, s = value, index, self
}));
console.log(unique)

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.