What is the best way to create a new array by filtering based on values from another array of objects using JavaScript?

I am struggling to comprehend how to iterate through an array within an array and extract only the presents modified by the scoreChild. Result1 currently includes the name as well, making it difficult for me to understand.

  const wishesData = [
    {
       name: "Peter",
      presents: ["coffee", "holidays"]
    },
    {
       name: "Mario",
      presents: ["coffee", "videogames"]
    },
    {
       name: "Amanda",
      presents: ["computer", "tattoo"]
    },
    {
      name: "David",
      presents: ["car","clothes"]
    }
  ]
  const scoresData= [
    {
      name: "Peter",
      score: 10
    },
    {
      name: "Mario",
      score: 6.3
    },
    {
       name: "Amanda",
      score: 1.1
    },
     {
       name: "David",
      score: 8
    }
  ]

  const childScore = scoresData.find(s=>s.name=== "Amanda").score

  console.log("Amanda score",childScore)

const result1 = wishesData.filter((ele)=>{
 
console.log("estos childScore=>",childScore)
  if(ele.name === "Amanda"){
    if(childScore>7){
    return ele.presents
  } else if(childScore<7 || childScore>5) {
    return  [...ele.presents, "coal"]
  } else if (childScore<5){
    return ele.presents.slice(0,1).concat("coal")
  }
  }

})

console.log(result1)

This is the expected result: result1 = ["car","coal"], indicating that each time the name of the child changes, the array will display the presents they "deserve" based on their score.

Answer №1

It appears that you are seeking to implement different behavior based on the score.

In the scenario provided, the final test within this function will never be reached

  (ele)=>{
 
  console.log("estos childScore=>",childScore)
  if(ele.name === "Amanda"){
    if(childScore>7){
    return ele.presents
  } else if(childScore<7 || childScore>5) {
    return  [...ele.presents, "coal"]
  } else if (childScore<5){
    return ele.presents.slice(0,1).concat("coal")
  }
  }

}

due to the section

else if(childScore<7 || childScore>5) {
        return  [...ele.presents, "coal"]
      }

which will always evaluate to true, perhaps using && instead of || was intended

Additionally, if you only require the presents value, filter is not suitable as it necessitates a boolean outcome to form a new array with matching values.

In this case, utilizing the reduce method may be more appropriate:

const result1 = wishesData.reduce((acc, ele)=>{
  console.log("estos childScore=>",childScore)
  if(ele.name === "Amanda"){
    if(childScore>7){
      return ele.presents
    } else if(childScore<7 || childScore>5) {
      return  [...ele.presents, "coal"]
    } else if (childScore<5){
      return ele.presents.slice(0,1).concat("coal")
    }
  }
 return acc;
})

I hope this clarifies your query! :)

Edit: The inner section can be simplified to

if(childScore>7) return ele.presents;
if (childScore<5) return ele.presents.slice(0,1).concat("coal");
return [...ele.presents, "coal"];

or alternatively,

return childScore>7 ? ele.presents : [...(childScore < 5 ? ele.presents.slice(0,1) : ele.presents), "coal"];

for a concise approach (considering that [ele.presents[0]] may enhance readability compared to ele.presents.slice(0,1))

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

When attempting to reload a single page application that utilizes AJAX, a 404 error is encountered

Recently, I've been working on coding my personal website and have successfully created a single page application using ajax. The content is dynamically loaded between the header and footer whenever a navigation bar link is clicked. To enable the back ...

"Using Angular, when $event is triggered on multiple child elements, each child

I am facing an issue with my html element in the application: .html <a (click)="onOpen($event)"> <i class="fa fa-file-text-o"></i> <p>Profile</p> </a> .ts onOpen(event):void { console.log( event.target ) ...

Creating a custom filter with ngx-pagination

Having trouble with filtering in Angular 7 + Electron 4 while using ngx-pagination. I followed the steps mentioned in the documentation, but encountered an error Uncaught Error: Template parse errors: The pipe 'stringFilter' could not be found ...

Utilize a script to interact with CasperJS

When it comes to running my CasperJS script, I typically do so from the command line interface using this command: casperjs --ignore-ssl-errors=true --ssl-protocol=any scrape.js In order to fully automate the process, I am now looking into calling the sc ...

Utilizing Express Session with Vue CLI in a Node.js Environment

Developing a nodejs backend for my Vue application has brought up a challenge regarding user sessions and database operations. I initially tried using express-session, but the sessions appeared as undefined in subsequent requests. How can I address this is ...

Creating Dynamic Menus with Material UI

I am currently working on rendering a Material UI Menu for each of my JSX Button Elements. However, all of my Menu Items are currently stacked on top of each other, and I want to be able to display only the Menu related to the clicked Button. Check out th ...

Duo and reference loop

I'm trying to learn how to use backreferences in JavaScript. I have an array and want to replace it within a string. Here's what I've attempted so far: var items = ["book", "table"]; var sentence = "The $1 is on the $2"; var newSentence ...

What is the process for linking my MongoDB database to my laptop?

I recently created a MongoDB account and attempted to connect it to my laptop, but unfortunately I encountered an error during the process. Below is the code snippet for my Mongoose connection: mongoose.connect( 'mongodb+srv://${process.env.MONGO_D ...

Passing a pointer to a function in C - the right way to do it

I'm working on a project in C involving a cellular automaton and I've run into a snag with a function called "get." How can I modify "get" to accept a map and return the value at a specific position? As I delve into pointers and memory allocatio ...

Storing numerous sets of application credentials in Node.js using a specific design pattern

As I develop a node.JS server that communicates with Microsoft APIs, the server manages multiple applications created in Azure, each requiring a configured Client ID and Client secret. I have implemented a strategy to switch between these credentials based ...

Is it possible for me to designate variables as an array element?

<!doctype html> <html lang="en"> <head> <title>Favorite Foods</title> <meta charset="utf-8"> <script> var foodItem0 = prompt("Enter your favorite food"); var foodItem1 = prompt("Enter your second f ...

Entwine words around an immovable partition

Is it possible to create an HTML element that remains fixed in place even as the content on the webpage changes, with everything else adjusting around it? I am looking to add a continuous line that spans across a dynamic webpage. No matter how much conten ...

Get names with specific characteristics by using a Javascript object that acts as an associative array

Can someone help me with my code? I'm trying to create an input box that, when I type in "A", will display the names of students who have earned "A" grades. I feel like I'm close to getting it right, but there's something missing. Any assist ...

I am experiencing difficulty with my Glsl shaders not loading properly on either the Liveserver or Github pages

I'm fairly new to the world of web development and I've been experimenting with incorporating 3D images into a webpage. In one of my projects, I'm utilizing .glsl files to load textures and shaders. Everything works smoothly when I run my co ...

Combine two sets within a single array if their values match

I currently have a set of pairs stored in the same array: [ ["ID" => 0, "User" => "Test", "Type" => 3, "Target" => "Caris"], ["ID" => 1, "User" => "Test1", "Type" => 3, "Target" => "Caris"], ["ID" => 2, "User" => "Test2", ...

What are the steps to clipping a canvas using CSS clip-path?

When it comes to clipping a canvas, there are multiple methods that can be used. One way is to create a path with getContext('2d') and set globalCompositeOperation. Another method involves using -webkit-clip-path or clip-path, though the latter m ...

Solving the IE7 total crash issue

I am currently using Joomla with VirtueMart for my e-commerce website. I have also installed a plugin to VirtueMart for product sliding. While the gallery works fine, under IE7, all the links on the page become unclickable and the entire page seems to be ...

Working with PHP Multidimensional Associative Arrays: How to Retrieve a List of Keys?

Here is a look at the data I have: [204] => Array ( [1] => Array ( [leads] => 9 ) [2] => Array ( [leads] => 15 ) ) [200] => Array ...

Retrieve information from a changing HTML table

I am working on a nodejs express project that features a Dynamic Table within my application. Users can add or remove rows and enter values into cells, but I am struggling to extract these values from the table without using jquery. My goal is to then inse ...

What is the process for determining a total value by utilizing multiple inputs with angular reactive forms?

Currently, I am attempting to calculate either the discount percentage or the discount amount from the list price using Angular 6 reactive forms. form.component.html (simplified) ... <form [formGroup]="productForm"> <mat-form-field class=" ...