Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify and manipulate JavaScript array

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

like image 364
Gino Avatar asked Mar 01 '20 19:03

Gino


People also ask

How do you modify an array in JavaScript?

To change the value of all elements in an array: Use the forEach() method to iterate over the array. The method takes a function that gets invoked with the array element, its index and the array itself. Use the index of the current iteration to change the corresponding array element.

How do you manipulate an array of objects in JavaScript?

const arr1 = [ {id:'124',name:'qqq'}, {id:'589',name:'www'}, {id:'45',name:'eee'}, {id:'567',name:'rrr'} ]; const arr2 = [ {id:'124',name:'ttt'}, {id:'45',name:'yyy'} ]; We are required to write a JavaScript function that takes in two such objects.

Can you change the elements in an array?

To replace an element in an array: Use the indexOf() method to get the index of the element you want to replace. Call the Array. splice() method to replace the element at the specific index. The array element will get replaced in place.


1 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!

like image 185
norbitrial Avatar answered Oct 02 '22 21:10

norbitrial