Looping through an array and appending distinct elements to a fresh array

I am currently facing an issue and seeking feedback on how to resolve it.

Below is the JSON data:

  questions: [
    {
      question: 'lala',
      answer: 'papa',
      categories: ['Handla']

    },
    {
      question: 'xxxx',
      answer: 'yyyy',
      categories: ['Reklamation']
    },
    {
      question: 'abcefg',
      answer: 'gooooogle',
      categories: ['Reklamation']
    }
  ]

My objective is to loop through this question array, extract and append ALL the object.categories to a new array, and then eliminate any duplicate entries. So, the desired output should be:

["Handla", "Reklamation"]

Answer №1

The ES6 Set makes it simple to eliminate duplicate values effortlessly. Start by merging all your categories into a single array:

const questions = [
    {
      question: 'lala',
      answer: 'papa',
      categories: ['Handla']

    },
    {
      question: 'xxxx',
      answer: 'yyyy',
      categories: ['Reklamation']
    },
    {
      question: 'abcefg',
      answer: 'gooooogle',
      categories: ['Reklamation']
    }
  ];
const flattened = questions.reduce((prev, curr) => [...prev, ...curr.categories], []); // ['Handla', 'Reklamation', 'Reklamation']
const unique = Array.from(new Set(flattened));
console.log(unique);

Answer №2

To achieve this, one can utilize the map() method along with ES6 Set and spread syntax ...

const data = {"questions":[{"question":"lala","answer":"papa","categories":["Handla"]},{"question":"xxxx","answer":"yyyy","categories":["Reklamation"]},{"question":"abcefg","answer":"gooooogle","categories":["Reklamation"]}]}

const result = [...new Set([].concat(...data.questions.map(o => o.categories)))]
console.log(result)

Alternatively, instead of map(), one can opt for using reduce() and employ Set as the accumulator parameter.

const data = {"questions":[{"question":"lala","answer":"papa","categories":["Handla"]},{"question":"xxxx","answer":"yyyy","categories":["Reklamation"]},{"question":"abcefg","answer":"gooooogle","categories":["Reklamation"]}]}

const result = [...data.questions.reduce((r, e) => {
  return r.add(...e.categories), r
}, new Set)]
console.log(result)

Answer №3

To accomplish this task efficiently, you can break it down into two simple steps. First, transform the questions into an array containing all categories. Then, filter out the unique items. Here's an example code snippet to help you achieve this:

const data = {
  questions: [{
      question: 'apple',
      answer: 'banana',
      categories: ['Fruit']
    },
    {
      question: 'blue',
      answer: 'green',
      categories: ['Color']
    },
    {
      question: '1',
      answer: '2',
      categories: ['Number']
    }
  ]
}

const categories = data.questions
  .reduce((prev, curr) => prev.concat(curr.categories), [])
  .filter((category, index, array) => array.indexOf(category) === index)

console.log(categories)

Answer №4

To easily obtain unique values from an array of categories, you can utilize the Set data structure in JavaScript.

var items = [{ item: 'apple', type: 'fruit', categories: ['Healthy'] }, { item: 'banana', type: 'fruit', categories: ['Healthy'] }, { item: 'cake', type: 'dessert', categories: ['Sweet'] }],
    uniqueCategories = [...new Set(items.reduce((result, { categories: category }) => result.concat(category), []))];

console.log(uniqueCategories);

Answer №5

You have the option to utilize plain JavaScript that is compatible with a wider range of browsers

var cats = [], questions = [{question: 'lala',answer: 'papa',categories: ['Handla']},{question: 'xxxx',answer: 'yyyy',categories: ['Reklamation']},{question: 'abcefg',answer: 'gooooogle',categories: ['Reklamation']}];

for (var i = 0; i < questions.length; i++) {
  var cat = questions[i].categories[0];
  if (cats.indexOf(cat) == -1) cats.push(cat);
}
console.log(cats);

A more contemporary approach:

const questions = [{question: 'lala',answer: 'papa',categories: ['Handla']},{question: 'xxxx',answer: 'yyyy',categories: ['Reklamation']},{question: 'abcefg',answer: 'gooooogle',categories: ['Reklamation']}];
let cats = [];

questions.forEach(function(q) {
  var cat = q.categories[0];
  if (cats.indexOf(cat) == -1) cats.push(cat);
});
console.log(cats);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Code in JavaScript: Generating Random Number within a Loop

Can anyone help me come up with a unique JavaScript loop that can guess a correct number within the range of 1-500? I want each iteration of the loop to generate a new number that has not been guessed before, but it should guess in a random order. For ex ...

Combining Django with the powerful Vue3 and lightning fast Vite

I'm in the process of upgrading my multipage app from Vue2 with webpack to Vue3 with Vite. After successfully rendering my Vue3 components on my Django templates, I am now facing a challenge - setting component variables on the Vue app using the Djan ...

Javascript animation functioning for a singular item within a list

As I continue practicing my skills in Javascript and HTML, I stumbled upon this intriguing list known as "item/adapter", similar to what we refer to as adapters in Android. While the process of adding them programmatically to my div is working smoothly, I& ...

Issues with APIs surfaced following the transition from DataGridPro to DataGridPremium

In my current project, we initially implemented the MUI X DataGrid but later switched to DataGridPro due to business requirements. Recently, we upgraded our plan from Pro to Premium which has caused some unexpected issues in our existing code. I am using " ...

What steps are involved in setting up a local server on my computer in order to create an API that can process http requests from Flutter?

New to API creation here, so please be patient. I plan to eventually host my API on a more robust server, but for now, I want to get started by setting something up locally on my PC to work on backend functions. The API goals include: Verify incoming requ ...

What is the best way to tally the number of fields in a JSON file based on their values

I'm relatively new to JavaScript and have a question that may seem basic. I've been struggling to find the answer, possibly because I'm not using the correct terminology. My goal is to count the number of "active" fields in a JSON file that ...

Presenting a Random Term from an Array in Dual Locations

<input type="button" id="btnSearch" value="Search" onclick="myFunction();" /> <div id="message"> <p></p> </div> <br> <div id="message"> <p></p> </div> <script type="text/javascript"&g ...

Updating the content with HTML and JavaScript

Hello everyone, I am currently working on a project to change the content of a div using JavaScript for educational purposes. Here is what I have done so far - <div id="navbar"> ... <ul> <li> <text onclick="getWordProcessing() ...

Error in jQuery sortable function occurs when dragging multiple elements

When using the sortable() function on multiple lists, I encountered a persistent bug. To drag more than one item, I added the following code to the start function: e.item.siblings(".selected").appendTo(e.item); However, a new issue arose where the plac ...

What advantages come from caching the document object for improved performance?

Usually, I cache DOM objects used in a script. However, recently I found myself having to reference the document object within a jQuery wrapper. I started questioning whether caching $(document) is necessary since there's only one document object per ...

What is the best way to swap out every instance of an array?

There are two arrays that I'm working with, The first array is defined as var symbols = ['A', 'B'];, and the second array is defined as var num = ['3', 'A', '5', '4']; I am looking for a so ...

Refreshing dynamically added rows through ajax updates

I'm struggling to clearly articulate my problem. Currently, I have a function that retrieves values from a database using ajax and then dynamically adds each result as a row in a table. This allows users to edit or delete any row as needed. I'm ...

What could be causing the npm mysql module to malfunction when trying to initiate the 'connect()' function in a separate .js file?

When I call require('mysql') and use the function connect() everything works fine. However, if I try to call the 'connect()' function in another file, it throws an error saying connection.connect is not a function... Any suggestions on ...

using ng-show to display array elements

There is a syntax error showing up on the console for the code below, but it still functions as intended. Can someone help identify what I might be missing? <p class="light" data-ng-show="selectedAppType in ['A1','A2','A3' ...

Can you explain how the functionality of setState operates within React in this specific situation?

I've been working on updating the state of an object in my array. I managed to get it done, but I'm a bit confused about how it works. toggleVisited = countryCode => { var countries = [ ...this.state.countries ]; var countryToChange = c ...

The array formations are validated and confirmed

What strategies can be employed to tackle a problem of this nature? Given two integers, N and K, we must determine the number of valid arrays that satisfy specific conditions: The sum of elements in the array must equal N K times each element is greater ...

Implement lazy loading functionality in Django to dynamically load data as the user scrolls

Currently, I am developing a web application using Django to showcase the interface and how content is loaded. In my database, there could potentially be thousands of entries, and I am looking for a way to load only a certain number at a time to minimize ...

Express JS res.send() with an array response data is posing a concern during the Checkmarx scan

When using the axios library in my express middleware to retrieve responses from APIs, I encountered a security concern raised by Checkmarx scan report. router.post(someurl,req,res) { axios .get(someurl) .then((response=>{ **res.send(response.data);**/ ...

Tips for optimizing AngularJS performance with large scopes

Currently, I am working on an Angular app for my company and have encountered a major issue. The app has become extremely slow, even after trying to optimize it using techniques like onetimebind and track by. Despite initial improvements, the performance i ...

Is there a way to segment a string into words using a dictionary and finding the longest match in JS/Jquery?

Imagine you have a string like this: var str = "thisisinsane"; and a list of words from a dictionary such as: var dic = [ "insane", "i", "is", "sin", "in", "this", "totally" ]; How can we separate the words in str? In this specific case, there a ...