Modify and manipulate JavaScript array

Viewed 140

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

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!

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

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

Related