Obtain an array containing only unique values from a combination of arrays

Is there a simple way or plugin that can help me combine values from multiple arrays into one new array without duplicates?

var x = {
  "12": [3, 4],
  "13": [3],
  "14": [1, 4]
};

The resulting array should only contain unique values:

[1, 3, 4];

Answer №1

To achieve this, you can utilize the ES6 spread syntax along with the Object.values method.

var numbers = {
  "12": [3, 4],
  "13": [3],
  "14": [1, 4]
}

const result = [...new Set([].concat(...Object.values(numbers)))]
console.log(result)

An alternative solution using the Lodash library

var numbers = {
  "12": [3, 4],
  "13": [3],
  "14": [1, 4]
}

const result = _.uniq(_.flatten(_.values(numbers)))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer №2

To traverse through a set and reduce an array, you can utilize the array#from method along with set and array#reduce.

var example = {"12": [3, 4],"13": [3],"14": [1, 4]};
    result = Array.from(new Set(Object.values(example).reduce((accumulator, currentValue) => accumulator.concat(currentValue), [])));
console.log(result)

If you want to extract all values from your object and create an object to retrieve keys from it, you can do that as well.

var example = {"12": [3, 4],"13": [3],"14": [1, 4]};
    result = Object.keys(Object
                        .values(example)
                        .reduce((accumulator, currentValue) => (currentValue.forEach(value => accumulator[value] = true), accumulator),{})
                        ).map(Number);
console.log(result)

Answer №3

To retrieve all keys and arrays, iterate through them as shown below:

var resultArray = [];
for (var key in object) {
    for (var index = 0; index < object[key].length; index++) {
        if (resultArray.indexOf(object[key][index]) === -1) {
            resultArray.push(object[key][index]);
        }
    }
}

https://jsfiddle.net/80c8ctuo/

Answer №4

To retrieve all arrays, utilize the Object.values method and then combine them into a single array using concat. After that, eliminate duplicates by utilizing filter.

const x = {"12": [3, 4],"13": [3],"14": [1, 4]};
const result = [].concat.apply([], Object.values(x)).filter((el, i, a) => i === a.indexOf(el));
console.log(result)

Answer №5

If for some reason the item comes from the output of JSON.parse:

var j = '{ "12": [3, 4], "13": [3], "14": [1, 4] }'

var a = [], x = JSON.parse(j, (k, v) => (a[v] = +v, v))

console.log( a.filter(isFinite) )

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

While using jQuery, it was discovered that the name attribute could be changed within the .each() function when working in console.log. However

I'm attempting to modify the name attribute of a cloned table row with the following code: var ipCount = 2; $("#input_form").on("click", "#add_input_param", function() { $('#input_param tr').eq(1).clone().find('input').val ...

What is the method for displaying an object as JSON on the console in Angular2?

I've been utilizing a service to input my form data into an array within my angular2 application. The information is organized in the following manner: arr = [] arr.push({title:name}) After executing console.log(arr), it displays as Object. However, ...

Error Type: TypeError when using Mongoose's FindOneAndUpdate function

I am encountering difficulties while trying to implement a findOneAndUpdate query. //UserController UserDAO ['findOneAndUpdate'](userId, {& ...

Record every action taken in the browser and compile it into a detailed HTML report

I am looking for a way to record and display all the browser actions performed in a test script in an HTML report. I am using protractor along with protractor-html-screenshot-reporter for reporting purposes. Is there any tool or API available that can he ...

Angular does not completely erase everything

Having some issues with file deletion while working on angular and typescript. My setup involves three interfaces: Project, SubProject, and Position. When a subproject is added to the selected project, it gets included in the subProjectIds list of the Proj ...

Original: Generic for type guard functionRewritten: Universal

I have successfully created a function that filters a list of two types into two separate lists of unique type using hardcoded types: interface TypeA { kind: 'typeA'; } interface TypeB { kind: 'typeB'; } filterMixedList(mixedList$: ...

`Generating an ever-changing masonry layout on a website using live data`

I'm currently working on a new web project and I want to incorporate a masonry view for the images on the homepage. The plan is to host this project on Azure, using blob storage for all the images. My idea is to organize the images for the masonry vi ...

Convert an array into a JSON object for an API by serializing it

Currently, I am working with Angular 12 within my TS file and have encountered an array response from a file upload that looks like this- [ { "id": "7", "name": "xyz", "job": "doctor" ...

Utilizing Unix timestamps for x-values while displaying dates as x-labels in an ECharts line chart

I'm struggling with incorporating date-converted unix timestamps as values in my ECharts graph. The x-axis of my chart is meant to display the recording time for each buy or sell price, represented by respective lines. Everything functions properly wh ...

Is there a problem with Framer Motion exit and AnimatePresence in Next.js?

Why isn't my exit prop or AnimatePresence working as expected? This is my custom variant: const imgVariant = { initial: { opacity: 0, y: -100, }, animate: { opacity: 1, y: 0, transition: { type: " ...

I'm having trouble configuring the header in my Node/Express route

Using Node and the Express framework for my backend, along with React for my frontend, all coded in Typescript. The elastic search client is responsible for fetching data on the backend, but I don't believe that's where the issue lies. I'm ...

Populate Vue 3 Element-plus Virtualized Table with actual data

As a newcomer to frontend development, I am currently working on integrating Element-plus Virtualized Table with actual data. Here is the basic structure of the example: const generateColumns = (length = 10, prefix = 'column-', props?: any) => ...

Checkbox remains selected even after the list has been updated

I am currently dealing with an array of objects where each object has a property called "checked." When I click on a checkbox, it becomes checked. However, when I switch to another list, the checkmark remains even though it should not. Here's an examp ...

Tips for sorting through JSON Data to isolate a particular day

I developed a Food-App that displays a different menu every day. I retrieve the local JSON Data using Axios and attempt to filter the mapped menu with .filter. My issue lies in not being able to filter specific days. I attempted to restructure the JSON Da ...

Is there a way to directly display all the content in pagination format without a print preview option?

I have been tasked with implementing a feature that involves displaying content using pagination and allowing users to print all the content at once with a single click on a print button. However, I am currently experiencing an issue where clicking the pri ...

Checking conditions sequentially in Angular

I have a unique use case that requires me to verify certain conditions. If one condition fails, I should not proceed to the next one. Instead, based on the failed condition, I need to display a dialog with a title and description explaining what went wrong ...

Choose all the HTML content that falls within two specific tags

Similar Question: jquery - How to select all content between two tags Let's say there is a sample HTML code as follows: <div> <span> <a>Link</a> </span> <p id="start">Foo</p> <!-- lots of random HTML ...

In JavaScript, the input box is set to automatically capitalize the first letter, but users have the ability

How can I automatically capitalize the first letter of a user's name input, but allow for overrides like in the case of names such as "de Salis"? I've read on Stack Overflow that CSS alone cannot achieve this with text-transform:capitalize;, so ...

Leverage Angular to highlight updated items within a list

My goal is to synchronize data, so I have a data object that holds the current state. Whenever this state changes, I want to mark the object with an attribute for filtering purposes during syncing. Here is the structure of the object: data = { type1: [ ...

Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18. In my HTML code, there is a <p> element with id="result", an input with id=&quo ...