An array of objects in JavaScript is populated with identical data as the original array

I am attempting to gather all similar data values into an array of objects. Here is my initial input:

var a = [{
    name: "Foo",
    id: "123",
    data: ["65d4ze", "65h8914d"]
  },
  {
    name: "Bar",
    id: "321",
    data: ["65d4ze", "894ver81"]
  }
]

The desired result is:

["65d4ze"]

I have tried looping through the object to achieve this outcome, but I have become quite perplexed... I am unsure how to determine if the result exists in all data arrays.

var a = [{
        name: "Foo",
        id: "123",
        data: ["65d4ze", "65h8914d"]
      },
      {
        name: "Bar",
        id: "321",
        data: ["65d4ze", "894ver81"]
      }
    ],
  b = [],
  c = []
a.forEach(function(object) {
  b.push(object.data.map(function(val) {
    return val;
    })
  );
});

console.log(b);

Answer №1

You have the option to utilize data mapping to extract the shared values using Array#map, Array#reduce, Array#filter, Set, and Set#has.

var array = [{ name: "Foo", id: "123", data: ["65d4ze", "65h8914d"] }, { name: "Bar", id: "321", data: ["65d4ze", "894ver81"] }],
    key = 'data',
    common = array
        .map(obj => obj[key])
        .reduce((arr1, arr2) => arr2.filter(Set.prototype.has, new Set(arr1)));

console.log(common);

Answer №2

To filter the first array based on the presence of values in other arrays, utilize the Array#filter method along with the Array#every method.

let result = initialArray[0].data.filter(value => remainingArrays.every(array => array.data.includes(value)));

var initialArray = [{
    name: "Foo",
    id: "123",
    data: ["65d4ze", "65h8914d"]
  },
  {
    name: "Bar",
    id: "321",
    data: ["65d4ze", "894ver81"]
  }
];

let result = initialArray[0].data.filter(value => remainingArrays.every(array => array.data.includes(value)));

console.log(result)

Answer №3

let array = [{
      name: "Foo",
      id: "123",
      data: ["65d4ze", "65h8914d"]
    },
       {
          name: "Bar",
          id: "321",
          data: ["65d4ze", "894ver81"]
    }
  ],
  object = {};
array.forEach(function(item) {
  item.data.forEach(function(dataItem) {
    if (!object.hasOwnProperty(dataItem)) {
      object[dataItem] = 0;
    }
    object[dataItem]++;
  });
});
resultArray = []
for (let key in object) {
  if (object.hasOwnProperty(key)) {
    if (object[key] > 1) {
      resultArray.push(key)
    }
  }
}
console.log(resultArray);

Answer №4

Utilize the flatten method within the array:

let x = [{
        name: "Alice",
        id: "456",
        data: ["65d4ze", "65h8914d"]
      },
      {
        name: "Bob",
        id: "654",
        data: ["65d4ze", "894ver81"]
      }
    ],
  y = [],
  z = []
x.forEach(function(obj) {
  y.push(obj.data.map(function(value) {
    return value;
    })
  );
});

console.log(y.flatten());

Answer №5

To find items with the same occurrence in all objects within an array, utilize the reduce and concat functions for each data array, analyzing the count of each item.

If all objects across the array contain the same item, it will be returned at the end of the process.

Keep in mind that this method is effective for extracting items with consistent occurrences throughout all objects in the array. Items with duplicates that do not meet this criteria will not be extracted.

let a = [{name: "Foo",id: "123",data: ["65d4ze", "65h8914d"]},{name: "Bar",id: "321",data: ["65d4ze", "894ver81"]}];

let arr = a.reduce((prev,next) => prev.data.concat(next.data));
let counts = {};
let result = [];
for (var i = 0; i < arr.length; i++) {
  var num = arr[i];
  counts[num] = counts[num] ? counts[num] + 1 : 1;
}

for (let i in counts) {
    if (counts[i] === a.length) {
        result.push(i);
    }
}
console.log(result);

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

An error occurred stating "No matching closing tag found for "<%" when attempting to include the file

While attempting to include other .ejs files using the same syntax, everything works perfectly except when including my _show.ejs file. I am unsure where the issue lies, whether it is in the index.ejs or _show.ejs file. This is my index.ejs File <!-- i ...

Why is the result displaying as 0 instead of 0.0?

After declaring an array of 10 elements and initializing it with values ranging from 0.0 to 9.9, I encountered an issue where the output displayed 0 instead of 0.0. Can anyone explain why this is happening? #include <iostream> using namespace std; i ...

What is the best way to change function.bind(this) to an arrow function in a react native application?

I am attempting to convert my function into an arrow function, but I keep encountering an error of undefined when passing props. <TextInput style={styles.input} value={formState.inputValues.title} onChangeText={textCh ...

Downloading Laravel Excel Files via an Ajax Call

Is it possible to generate an Excel file using Laravel with PHPSpreadsheet (PHP lib) and then send the XLSX file to the frontend for download? JSX Section axios .get( "/excel/export/dashboardTable", {} ) .then(resp => { //success call ...

Can you delete specific rows or columns in an Excel VBA array?

Creating an array from a selection in Excel can be problematic when considering hidden rows. For instance, if columns A, B, and C contain data but column B is hidden, the resulting array will still show 3 columns and 4 rows. Is there a possible solution ...

Utilizing JavaScript to conceal div elements within a ul container

How can I hide specific div tags inside a ul tag using JavaScript? All div tags are currently getting hidden when I use the id of the ul tag. However, I need only the first div tag to be shown and the rest to be hidden. Here is the HTML code: <ul clas ...

Convert my information to an XML document

Successfully, I have loaded the content of an XML file into my PHP document using the following method: $(document).ready(function () { $.ajax({ type: "GET", url: "abstimmer.xml", dataType: "xml", success: function ...

Exploring Tabletop.js to retrieve information from an array of data

Issue I am currently attempting to retrieve data from an array that contains two objects. I have implemented Tabletop.js to fetch the data from a public Google Spreadsheet, but I encountered an error in the console stating ReferenceError: object is not de ...

There are a total of 152 issues found in the index.tsx file within the react

Despite everything working correctly, I am continuously encountering these errors. Is this a common occurrence? What steps can I take to resolve them? I have developed my react application using Javascript instead of Typescript; however, I don't belie ...

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...

What's the most efficient way to iterate through this Array and display its contents in HTML?

I'm struggling to sort a simple array and I think the issue might be related to the time format. I'm not sure how to reference it or how I can properly sort the time in this array format for future sorting. //function defined to input values ...

Storing information within a Express application using Postgres

Recently, I've been delving into the world of Express and experimenting with a program that allows users to create events and invite others. While I know about using join tables to retrieve data, I'm curious if there's a way to organize the ...

Issues with Promise execution sequence in ExpressJS Middleware

I need help creating an Express Middleware that checks if the user/password pair in the authorization header exists in a JSON file for educational purposes. I have integrated this middleware into a simple unit converter app. The issue I'm facing is t ...

When the document is fully loaded on a page that has been dynamically loaded

Currently utilizing the following: $("#someDiv").load("ajax.html") The contents of "ajax.html" include a document.ready call: <script>$(function() { alert('works') })</script> I'm interested to know exactly when this callbac ...

Limit access to all pages, with the exception of the home page, in Django

During the development of my Django application, I organized the functionality into sub-functions and implemented them in individual apps. To display results on the homepage instead of redirecting to a sub-function app page, I utilized ajax and JavaScript. ...

Learning how to dynamically update a value in Angular based on user input

My goal is to dynamically change the output value based on user input using Angular. I have successfully implemented the functionality to increment the value, but unfortunately, when the input changes, the outputed value remains static. Below is my curren ...

When working with React.js, encountering the error message "Unexpected token export on export{default as

When attempting to import components into my newly installed app, I used the following syntax: import {Cards , Chart , CountryPicker} from '../components' I also created an index.js file with the following content: export {default as Cards} ...

.mouseleave() triggers when exiting a designated boundary area

I'm attempting to implement a roll-up feature for a div when the mouse is over another div. The issue I'm facing is that the roll-up div closes even if the mouse just exits through the bottom border. Is there a way to achieve this using JavaScrip ...

What is the best way to add multiple rows using a parameter in SQL?

My goal is to insert multiple rows in SQLite using the ionic framework. Inserting a single row works fine, as does running the following query: INSERT INTO categories (category_id, category_name, category_type) VALUES (1,"test",1),(2,"test again", 2); ...

How can a controller configure an AngularJS provider by passing options?

How can I pass configuration options to a provider from a controller? Below is an example of how to pass options/configurations to a provider from the controller: provider.js file: app.provider('contactProvider', function() { this.name ...