7

Here is an array example I have:

var array= ['business>management', 'News>Entertainment News', 'business>Entrepreneurship'];

I want this result:

['business', 'management', 'News', 'Entertainment News', 'Entrepreneurship']

It means, separate from this '>' No duplicate

This is an example of where I'm at but it just removes the arrow '>' jsfiddle

4 Answers 4

6

You can use reduce() and Set combination for example. Read from the docs:

The Set object lets you store unique values of any type, whether primitive values or object references.

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.

Please see a possible working solution.

const array = ['business>management', 'News>Entertainment News', 'business>Entrepreneurship'];

const result = array.reduce((a,c) => {
  c.split('>').forEach(e => a.add(e));
  return a;
}, new Set());

const unique = Array.from(result);

console.log(unique);

I hope that helps!

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

1 Comment

This is Perfect :)
2

try this one -

const array = ['business>management', 'News>Entertainment News', 'business>Entrepreneurship'];
let newArray = []
array.map((item)=>{
    let newData = item.split(">").map((itemIn)=>{ 
      newArray.push(itemIn) 
      return item
      })
    return newData
})
console.log(newArray)

Comments

2
Simplified

let array = ['business>management', 'News>Entertainment News', 'business>Entrepreneurship'];

let separated = array.map((item, ii) => {
    return item.split(">")
}).reduce((a, b) => a.concat(b)).filter((value, index, self) => {
    return self.indexOf(value) === index;
});

console.log(separated)

Comments

0

You could use .flatMap() with .split() to create an array of strings split by '>'. Then you can put these results into a Set to remove duplicates, and then back into an array using the spread syntax (...).

const array = ['business>management', 'News>Entertainment News', 'business>Entrepreneurship'];

const result = [...new Set(array.flatMap(str => str.split('>')))];
console.log(result);

If you can't use .flatMap() due to compatibility concerns, you can always use .map() and then flatten the array afterwards using .concat() which has much better browser comptability:

const arr = ['business>management', 'News>Entertainment News', 'business>Entrepreneurship'];

const result = [...new Set([].concat(...arr.map(s => s.split('>'))))];
console.log(result);

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.