What is the best way to filter an array based on the property of its inner array?

I am grappling with the following array of objects:

let a = [
    {
        b: [1, 11, 12],
        c: "a1"
    },
    {
        b: [2, 56, 1],
        c: "a2"
    },
    {
        b: [1, 2, 3],
        c: "a3"
    }
]

In search of an operation that is both simple and efficient, I wish to extract a second array from a that contains only elements with values exceeding 10 in their b arrays. For these selected elements, I want their corresponding b arrays to include solely the values greater than 10. The desired output is:

[
    {
        b: [11, 12],
        c: "a1"
    },
    {
        b: [56],
        c: "a2"
    }
]

While I could achieve this through traditional looping or using multiple steps such as filter(), I am hopeful for a more streamlined one-line solution. Any recommendations?

Answer №1

Here is an example using filter and reduce:

let items = [{numbers:[1,11,12],letter:"a1"},{numbers:[2,56,1],letter:"a2"},{numbers:[1,2,3],letter:"a3"}]

const result = items.reduce((acc, { numbers, letter }) => {
  // filter out numbers greater than 10
  const filteredNumbers = numbers.filter(num => num > 10);
  
  if (filteredNumbers.length)
    acc.push({ numbers: filteredNumbers, letter });
    
  return acc;
}, [])

console.log(result)

Answer №2

To achieve the desired result, you can utilize both .filter() and .map() in your code:

let data = [{
    values: [1, 11, 12],
    category: "a1"
}, {
    values: [2, 56, 1],
    category: "a2"
}, {
    values: [1, 2, 3],
    category: "a3"
}];

let filteredData = data.filter(({ values }) => values.some(val => val > 10))
         .map(obj => Object.assign({}, obj, {values: obj.values.filter(val => val > 10)}));

console.log(filteredData);
.as-console-wrapper {max-height: 100% !important; top: 0; }

Answer №3

To simplify your code, you can utilize the reduce and filter functions

const data = [{b: [1, 11, 12],c: "a1"},{b: [2, 56, 1],c: "a2"},{b: [1, 2, 3],c: "a3"}]


const result = data.reduce((output,{b,c})=>{
  const filteredValues = b.filter(value => value > 10);
  if(filteredValues.length){
    output.push( { b : filteredValues,c })
  } 
  return output
},[])

console.log(result)

Answer №4

Here is an easy method to accomplish this task.

let x = [
    {
        y: [5, 15, 25],
        z: "abc"
    },
    {
        y: [3, 33, 7],
        z: "def"
    },
    {
        y: [8, 9, 10],
        z: "hij"
    }
]

var output = [];
x.forEach((element) => {
var subElement = { z: element.z, y: element.y.filter((y)=> y > 20)}
if (subElement.y.length>0)
     output.push(subElement);
});

console.log(output)

Answer №5

const filteredResult = a.map((item) => {item.b.filter((bItem) => bItem > 10), item.c}).filter((item) => item.b.length == 0);

Answer №6

Some insightful responses above. Here's my perspective:

let filteredArr = originalArray.slice().filter(item => {
    item.values = item.values.filter(val => val > 20)
  return (item.values.length > 0) ? true : false;
})

Answer №7

UPDATE I have reviewed all the insightful answers provided here and I appreciate the effort everyone has put into sharing their ideas. After careful consideration, here is the solution I have come up with:

a.filter(x => x.b.some(y => y>10)).map((z) => {
    return {
        b: z.b.filter(zb => zb>10),
        c: z.c
    }
})

Explanation:

The 'a' array is filtered to only include elements where element 'b' contains at least one value greater than 10. The third element in 'a' does not meet this condition and is therefore excluded from the new array. After filtering, we get:

[
    {
        b: [1, 11, 12],
        c: "a1"
    },
    {
        b: [2, 56, 1],
        c: "a2"
    }
]

Subsequently, each element in the newly filtered array is mapped to a new array that retains the same 'c' value but only includes elements in 'b' that are greater than 10. This results in:

[
    {
        b: [11, 12],
        c: "a1"
    },
    {
        b: [56],
        c: "a2"
    }
]

I want to express my gratitude for your valuable inputs and contributions!

Answer №8

Instead of the standard solution, here is an alternative method using nested filters().

This approach hinges on the idea that if any element in the b array exceeds 10, then filtering it based on the previous condition will yield a non-empty array.

It's important to note that this procedure does not alter the original array, as it operates on a copy of the array passed to the filters.

let a = [
    {b: [1, 11, 12], c: "a1"},
    {b: [2, 56, 1], c: "a2"},
    {b: [1, 2, 3], c: "a3"}
]

let res = a.filter(
    ({b}, i, arr) => (arr[i].b = b.filter(x => x > 10)) && arr[i].b.length > 0
);

console.log(res);

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

Guide on integrating a plain Service/Provider into nest.js

I recently created a basic TypeScript class in nest.js called JwtTokenService.js. // JwtTokenService.js import { Injectable, Optional } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { JwtPayload } from ' ...

What could be causing the issue with setting a value for a JSON array in the following method?

Consider this piece of code that I'm currently working with: compareList[productName] = productID + ',' + productHref; console.log(productName + ' ' + productID + ' ' + productHref + ' ' + compareList.length); ...

Using recycled frame buffers in a threejs fragment shader

I'm currently working on a project to develop an app that emulates the effect of long exposure photography. The concept involves capturing the current frame from the webcam and overlaying it onto a canvas. As time progresses, the image will gradually ...

Displaying XML data in an HTML table

Encountered a challenge while fetching data from an external XML document using JS. Following the w3schools tutorial for AJAX XML, but faced an issue I couldn't resolve. The XML structure is as follows: <root> <document-id> <author ...

Unleash the power of a module by exposing it to the global Window object using the dynamic

In my development process, I am utilizing webpack to bundle and manage my TypeScript modules. However, I am facing a challenge where I need certain modules or chunks to be accessible externally. Can anyone guide me on how to achieve this? Additional conte ...

The width:auto attribute for images in ie6 is not functioning as expected

I am facing a challenge with dynamically changing and resizing an image element to fit its container. My current approach involves: Resetting the image: // Ensuring the 'load' event is re-triggered img.src = ""; // Resetting dimensions img. ...

Showcase -solely one property object- from numerous property objects enclosed within an array

Hello, I am seeking assistance as I have recently begun learning about angularJS. I am working with objects that have keys such as: scope.eventList=[]; for(){ var event = { id : hash, ...

What steps can you take to address Git conflicts within the yarn.lock file?

When numerous branches in a Git project make changes to dependencies and use Yarn, conflicts may arise in the yarn.lock file. Instead of deleting and recreating the yarn.lock file, which could lead to unintended package upgrades, what is the most efficie ...

Tips for deploying an Angular application with Node.js

Currently, I've set up a nodejs backend by following a tutorial to integrate tweets into the frontend of my application. As I prepare to deploy to a development server, I have successfully built the frontend using ng build --prod. However, I am facin ...

NodeJS application experiencing significant delays due to slow response times from MySQL database queries

Currently, I am in the process of learning about Node.js. Through utilizing Express and Node-Mysql, I have been able to effectively query my mysql database and return the outcomes as JSON to the client. However, there seems to be a significant delay. Eve ...

Switch out the content within a div upon selection

I'm currently working on a palette board project and facing some challenges when switching to a different theme. The initial page is set to have a Warm color palette, but I intend to alter this once the user clicks on the All theme option. Users wil ...

Error: The function .join is not recognized by the sockets.io library in a Node.js client-server environment

I'm currently working on developing a chat app using node and vue js, and I've encountered an issue with the socket.io library. Specifically, I keep receiving an error stating that ".join is not a function" when trying to use it in my server-side ...

What is the best way to halt an event using jQuery?

My question is about handling events on a webpage. I am interested in triggering a jquery method when the user clicks a link to navigate away from the page. In this method, I need to perform some checks before allowing the user to leave, so I plan to use: ...

Adjusting solely the numeric values within a combined array containing both associative and numerical elements

When I send an SQL query to a table in my program, it returns a resource that I use the function mysql_fetch_array() on. The first argument is the results resource from the SQL query, but if you omit the next argument, it defaults to returning an array wit ...

Click the button to insert a time stamp into the text area

Whenever the id=dodaj_godzine_button is clicked, I would like to add the current time to id=formularz_wpis_tresc (as a string). I attempted to do this using the code below, but it seems to be malfunctioning. $("#dodaj_godzine_button").click(function(){ ...

Using Ramda, learn how to transform a flat list into a hierarchical one

Looking to transform the given list into a hierarchical structure with nested children fields. The 'parentId' attribute has been omitted for clarity, as it will be used in the transformation process using Ramda's immutable behavior. const x ...

Popovers in Bootstrap 4 do not have clickable Custom Forms

I find it strange that in Bootstrap 4, only custom forms are not clickable in the Bootstrap popover. It's interesting how default forms in Bootstrap 4 work just fine. Any suggestions on how to resolve this issue? Below is my code. Thank you for you ...

Fixing the Angular2 glitch: 'Uncaught TypeError: Cannot read property 'apply' of undefined'

Seeking solutions: How can I fix the "Uncaught TypeError: Cannot read property 'apply' of undefined" error that keeps showing up in the console of my Angular2 application? Any helpful insights are appreciated! ...

What is the equivalent of preg_replace in PHP using jquery/javascript replace?

One useful feature of the preg_replace function in PHP is its ability to limit the number of replacements made. This means that you can specify certain occurrences to be replaced while leaving others untouched. For example, you could replace the first occu ...

How to efficiently search MongoDB for existing records and group them by unique array values

My dataset is structured like this: { "_id" : 1, "category" : [ { "name": "category1" }, { "name": "category2" } ], "event": [ { type: "house" ...