Using filter in JavaScript to manipulate an array of array objects: what you need to know!

Currently, I am working with an array that contains the following values:

var array1 = ['new_user', 'promotion']

My task is to filter out an object from OBJc based on this array1:

OBJc = [
    {"id": 1, "array_": ['promotion', 'test1']},
    {"id": 2, "array_": ['test444', 'test1']},
    {"id": 3, "array_": ['new_user', 'test1']}
]

The requirement is to filter this JSON data based on whether "array_" contains any of the values in array1.

The desired output would be:

[
    {"id": 1, "array_": ['promotion', 'test1']},
    {"id": 3, "array_": ['new_user', 'test1']}
]

Answer №1

const filteredCollection = OBJc.filter(object => object.array_.some(element1.includes))

Alternatively, using ES6 destructuring:

const filteredCollection = OBJc.filter({ array_ } => array_.some(element1.includes))

The goal is to evaluate each element in array_ against array 1 and retain only those that meet the specified criteria.

Answer №2

If filtering is what you seek, let's filter away.

OBJc.filter()

Now, the goal is to return true when your property contains a specific value, correct?

OBJc.filter(value => {
  return value['array_'].includes(x)
})

However, there are multiple values to consider, and you must determine if at least some of them are present in your list

OBJc.filter(value => {
  return array1.some(arrV => value['array_'].includes(arrV));
})

Alternatively, if you prefer concise one-liners:

OBJc.filter(value => array1.some(arrV => value['array_'].includes(arrV)));

Answer №3

Check out this solution:

let arr1 = ['new_item', 'special_offer']

jsonData = [
    {"id": 1, "array_": ['special_offer', 'test123']},
    {"id": 2, "array_": ['test456', 'test123']},
    {"id": 3, "array_": ['new_item', 'test123']}
]

const finalResult = jsonData.filter(object => {
    let isFound = false;
    arr1.forEach(element => {
        if (object.array_.includes(element)) {
            isFound = true;
        }
    });
    if (isFound) {
        return true;
    }
});

console.log(finalResult);

Answer №4

If you enjoy experimenting with boolean values, here's a solution for you.

const checkTruth = (a, b) => a || b;

const results = jsonData.filter(item => {
    return item.list_.map( x => list1.map(y => y == x).reduce(checkTruth, false)).reduce(checkTruth, false);
});

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

Apps hosted on Heroku are restricted from accessing CORS, even within the platform's domain

I've been struggling with this problem for a while now. My Nuxt app and service are both hosted on Heroku. After ditching cors(), I added the following code: app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", '*&ap ...

Run a section of code located in a different file

I have defined some global functions in main.js like this: Vue.prototype._isMobile = function () { return $(window).width() < 768 } //Few more similar functions Now, I want to move these functions to a separate file called util.js: return (function ...

Create a full-width slider using Materialize CSS framework

When using materializecss to create a slider, I encountered an issue where the image is full width but not full height, causing scrollbars to appear. What changes can I make to ensure the slider fills out my screen without any scrollbars? Additionally, I ...

Submitting information through Ajax

Struggling to update a field in my database using AJAX. No errors in console, but the DB won't update. Anyone able to help? AJAX: function ajaxUpdate() { var arr = {var1: name, var2: age}; $.ajax({ url: 'aja ...

An error occurred in react-dates where the property 'clone' of null could not be read, resulting in a new DayPicker

I'm encountering an issue with the following code snippet: const [focusedInput, setFocusedInput] = useState('startDate'); const onFocusChange = fInput => { setFocusedInput(!fInput ? 'startDate' : fInput); }; <DayPickerRang ...

Transferring the value of a variable from Block to Global Scope in FIRESTORE

I'm currently working on an App in Firebase, utilizing FireStore as my primary Database. Below is a snippet of code where I define a variable order and set it to a value of 1. Afterwards, I update the value to 4 and use console.log to verify. Everyt ...

AngularJS factory problem

I attempted to utilize Angular JS by using a factory for my data structure... However, it seems to be malfunctioning. I simply added some basic json data to be returned by the factory, and as a result, the script stopped working. This is a fundamental ex ...

A guide to efficiently passing props in Quasar 2 Vue 3 Composition API for tables

I am encountering an issue while attempting to create a custom child component with props as row data. The error message "rows.slice is not a function" keeps appearing, and upon inspecting the parent data, I found that it is an Object. However, the props r ...

``Is there a way to retrieve the value of a textbox using a jQuery function?

I am attempting to retrieve the value of different textboxes within a for loop in a jQuery function. Here is my PHP code: <?php $qstid = $addnew334->id; $dd = DB::table('tbltplatematerial')->where('qteid',$qs ...

Discover the process of retrieving all workday dates using Angular

Currently, I am working on a project in Angular that involves allowing employees to record their work hours. However, I am facing a challenge in figuring out how to gather all the work dates and store them in an array. Here is what I have attempted so fa ...

Is it possible to utilize AngularJS' ng-view and routing alongside jade?

Currently, I am diving into the world of the MEAN stack. I noticed that Express utilizes jade by default, but I decided to experiment with it even though I can easily use html instead. When attempting to route with Angular, like so: ... body div(ng-view ...

Struggling to merge two variables together and receiving this error message: "mergedObject is not defined."

New to Node.js/Express and trying to combine two objects to save them to a collection. Any advice would be greatly appreciated! Thank you in advance for your time. This is what I've put together, but it's not functioning as expected: app.post( ...

Error message "Unable to load / invalid sound with zero-length duration reported on Chrome and Firefox."

Encountered an issue where / invalid sound zero-length duration was reported in Chrome and Firefox. However, the error only appeared in IE10. Here is the code snippet: foo = soundManager.createSound({ id: 'bar', url: '../music/ ...

What is the reason for memory allocation only occurring when geometry.elementsNeedUpdate is used?

When using a basic animate function like this: function animate() { geometry.elementsNeedUpdate = true; requestAnimationFrame( animate ); renderer.render( scene, camera ); } A memory allocation occurs even if no elements are changed. To address this, I ...

Navigating to the next page on a dynamic component in Angular 5 by

I'm uncertain if this scenario is feasible, but I have a page that fetches a list of items from an external API. There are currently 5 elements on the page, each acting as a link to its individual dynamically generated page through query strings. For ...

The toggling feature seems to be malfunctioning as the div section fails to display

I'm facing an issue with my Django project while working on a template. I want to toggle the visibility of a div element between hiding and showing, but the function I used isn't working for some reason. I borrowed the function from a different t ...

Tips for securely concealing an API key during website deployment on Netlify

Recently, I created a small website using Javascript just for fun and I'm looking to deploy it to Netlify. However, I've encountered an issue with the API key that the website uses. I'm struggling to figure out how to conceal this key. Curre ...

Utilize jQuery ajax to target a particular recurring input

I am using HTML code along with another jQuery loop. Within this loop, there is an input element that is also being looped. I am trying to manipulate it using jQuery Ajax... but I am facing an issue where only the first input element works properly. The re ...

Is your Cloud Functions task generating an Array when querying?

To access items and products in my database, I need to retrieve the "ean" field from the product and check if it matches the one in the request body. The structure of my database is as follows: "cart": { "items": { "0": {info here}, "1": {info ...

Arrange pictures and div elements in a horizontal layout

I am facing an issue with my code that is displaying 5 'cards' in a messed up layout instead of a straight line. I have tried to align them vertically, but some are still higher and not in the right positions. For reference, I want the layout to ...