user13513083
user13513083

Reputation:

Duplicate in array to how to remove it - JavaScript

Basically I have an array, like this:

const companies = [
  {
    name: "Company One",
    category: "Finance, Finance, Technology, Auto, Same, Same, same",
    start: 1981,
    end: 2004
  }
]

In category, I want to write a .map or if statement to find the value matches the value if so remove all the extra values (Same for example) and just leave one instance of it.

So far what I have done is this:

const newSingles = companies.map(function(company) {
  if (company.category === company.category) {
    console.log("cats match remove and leave one");
    //This is where I am stuck?!
  };
});

It's driving me a little crazy as I was going to use .pop() but not sure how to. What can I try next?

Upvotes: 0

Views: 66

Answers (3)

user13513083
user13513083

Reputation:

So thank you for all the help everybody, it is very kind to get help!

If I put all my categories in their own array:

const companies = [
  {
    name: "Company One",
    category: ["Finance", "Finance", "Technology", "Auto", "Same",
               "Same"],
    start: 1981,
    end: 2004
  }
]; 

Then do this:

companies.map(it => 
    it.category = it.category.reduce((previous, currItem) => {
        if (!previous.find(
                    x => x.toLowerCase() === currItem.toLowerCase()))
            previous.push(currItem);
        return previous;
    }, []));

That gives me an output of the following:

[
  {
    name: 'Company One',
    category: [ 'Finance', 'Technology', 'Auto', 'Same' ],
    start: 1981,
    end: 2004
  }
]

Again thank your for your help :)

Upvotes: 1

sulhadin
sulhadin

Reputation: 516

You should split your category and you need to find the unique values in your category array list. Try something like;

var category = ["Finance", "Finance", "Technology", "Auto", "Same", "Same", "same" ];
var uniques= category.filter((item, i, ar) => ar.indexOf(item) === i);

console.log(uniques);

With a little change, your new implementation would be something like this;

const newSingles = companies.map(function(company) {
const category = company.category.filter((item, i, ar) => ar.indexOf(item) === i);
  return {
   ...company,
   category
  }
});

And here is your new result;

[
  {
    name: "Company One",
    category:[ "Finance", "Technology", "Auto", "Same", "same"],
    start: 1981,
    end: 2004
  }
]

Upvotes: 0

swarfey
swarfey

Reputation: 1

Try Array.filter(), do not use an if statement inside .map()

Maybe this will help you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Upvotes: 0

Related Questions