Retrieve elements from an array based on the value of an object

I have a list of items that resembles the following structure:

var entries = [
  { sys: {id:"1"}, fields: "article1" },
  { sys: {id:"2"}, fields: "place1" },
  { sys: {id:"3"}, fields: "offer2" },
  { sys: {id:"1"}, fields: "article2" },
  { sys: {id:"1"}, fields: "article3" },
  { sys: {id:"3"}, fields: "offer2" },
  { sys: {id:"2"}, fields: "place2" }
];

My goal is to divide this set into 3 separate arrays based on their sys.id values. The desired output should be as follows:

var articles = [
  { sys: {id:"1"}, fields: "article1" },
  { sys: {id:"1"}, fields: "article2" },
  { sys: {id:"1"}, fields: "article3" }
];

var places = [
  { sys: {id:"2"}, fields: "place1" },
  { sys: {id:"2"}, fields: "place2" }
];

var offers = [
  { sys: {id:"3"}, fields: "offer2" },
  { sys: {id:"3"}, fields: "offer2" }
];

I've managed to achieve this by using a for loop, like so:

var places = [], offers = [], articles = [];

for (i=0; i<entries.length; i++) {
  if (entries[i].sys.id === "1") results.articles.push(entries[i]);
  else if (entries[i].sys.id === "2") results.places.push(entries[i]);
  else if (entries[i].sys.id === "3") results.offers.push(entries[i]);
}

However, considering that the initial dataset will be larger and more complex, I wonder if there is a more efficient method than using a basic for loop. Is there a faster and more optimal approach?

Answer №1

Here's a handy, reusable function that works well with [].filter():

function findById(obj){ return obj.searchId===this;}

var locations = entries.filter(findById, 1), 
 deals = entries.filter(findById, 2), 
 stories = entries.filter(findById, 3);

This function streamlines the code needed to iterate through specific cases compared to using traditional for-loops.

To further simplify and target individual cases, you can wrap it in another succinct function:

 function filterById(n){
    return entries.filter(function findById(obj){ 
      return obj.searchId===this;
    }, n);
 }

 var locations = filterById(1), 
 deals = filterById(2), 
 stories = filterById(3);

I used === to ensure strict equality checking between numbers and strings, but if desired, you can add "use strict" and change == to === within the filter() callback function.

Answer №2

To make it easier, you can use the filter method like this:

 entries.filter((item) => item.id === 1)

Answer №3

This is the way I approach it

const mapping = [
    ["1", "books"],
    ["2", "music"],
    ["3", "movies"]
].reduce((acc, pair) => {
    acc[pair[0]] = pair[1];
    return acc;
}, {});

const dataEntries = [
  { sys: {id:"1"}, fields: "book1" },
  { sys: {id:"2"}, fields: "song1" },
  { sys: {id:"3"}, fields: "movie2" },
  { sys: {id:"1"}, fields: "book2" },
  { sys: {id:"1"}, fields: "book3" },
  { sys: {id:"3"}, fields: "movie2" },
  { sys: {id:"2"}, fields: "music2" }
];

// Both the mapping and entries can be sourced from a dataset
// This allows for various sys.id values

// The hash will contain the final result
const resultHash = dataEntries.reduce((acc, item) => {
   const key = mapping[item.sys.id];
   acc[key] = acc[key] || [];
   acc[key].push(item);
   return acc;
}, {});

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 using RS256 with JWT, the private key will not be accepted

I've been attempting to generate a JWT using 'jsonwebtoken' with RS256. The keys were generated using the following command: ssh-keygen -t rsa -b 4096 -m PEM -f <filename> The private key output appears as follows: -----BEGIN RSA PRIV ...

Preserving the background image on an html canvas along with the drawing on the canvas

Can users save both their drawings and the background image after completing them? var canvas = document.getElementById("canvas"); // This element is from the HTML var context = canvas.getContext("2d"); // Retrieve the canvas context canvas.style.ba ...

Pug does not have access to computed properties within the dynamic class attribute of a Vue component

After attempting to dynamically toggle the className based on computed property and encountering issues in Pug, I found that manually setting 'true' to a className was the solution. Even after trying to reassign the computed property to a Pug var ...

Unpacking confidential data

Recently, I came across this code snippet that caught my attention. It's from a tutorial on custom contracts in C# serialization, which can be found at this link. The code seems to do well when serializing the fields of Brains.Brain, but there seems t ...

The requested module cannot be located, were you referring to "js" instead?

I am currently developing a React application using webpack and typescript. I have integrated the dependency react-financial-charts into my project, and it is properly specified in the package.json. Inside the node_modules directory, there are two folders ...

I'm having trouble getting FlowType.js to function properly

I have added the following code just before the closing </body> tag, but unfortunately, it seems like the type is not changing as expected. I am struggling to identify what mistake I might be making. Check out FlowType.JS on GitHub View the code on ...

I'm having trouble understanding why I can't access the properties of a class within a function that has been passed to an Angular

Currently, I have integrated HTML 5 geolocation into an Angular component: ... export class AngularComponent { ... constructor(private db: DatabaseService) {} // this function is linked to an HTML button logCoords(message, ...

Removing the previous value in React by shifting the cursor position - a step-by-step guide

I have successfully created a phone using React that saves the numbers in an input field whether you press the keys or use the keyboard. Although the phone is functioning well, I am facing an issue where pressing the delete button or backspace key always ...

Extracting date information from an HTML table for use in Highcharts

Trying to utilize HighCharts' HTML-table-to-chart script for generating a line graph from a table. Desiring to set a datetime x-axis, so the following steps have been taken: Utilizing Date.parse(this.innerHTML) to convert row headers into date stri ...

The usage of $('').switchClass in IE8 may cause an error when the switched class includes a color property

I have the following unique css classes .swap-format{ background-color: green; } .swap-format1{ background-color: orange; } .swap-format2{ color: purple; } Using these classes, I want to create an animation on the given div <div id="swap-clas ...

Error: The function you are trying to reference is undefined

I am facing an issue where I am receiving a "ReferenceError: doNotification is not defined" message when attempting to display a pop-up notification upon successful promise. Oddly enough, triggering doNotification on button click within my HTML works wit ...

While the data from Angular $resource can be viewed, it is not accessible in the code

As a newcomer to Angular, I'm facing a frustrating issue that I need help with. My $resource is fetching data from the server in key/value pairs like detail.name and detail.email. While I can access this data using {{detail.name}} in the view, I&apo ...

Ensure that JavaScript functions are executed sequentially without overlapping

Important : Absolutely no jQuery allowed I have developed four distinct functions and I am looking to execute them sequentially, one after the other in JavaScript without using jQuery. I have scoured the internet for a solution but unfortunately have not ...

Using PHP variables in JavaScript is not compatible

Currently, I am facing an issue where PHP variables inside the javascript code are not being echoed. When I try to echo the variables outside of the javascript, everything works perfectly fine. After carefully reviewing my code multiple times, I still cann ...

In JavaScript, is it possible to dynamically alter and showcase the value of a select tag?

My code snippet in the HTML file contains Javascript: <script> $(document).ready(function(){ $("#sub").click(function(){ var user_issue = $("#issue").val(); ...

The issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...

Retrieving the JSON data from an API using Laravel

Currently, I am experimenting with APIs and my latest project involves utilizing the Google Directions API within my application. To handle this, I have created a form to collect user input and generate the necessary URI directly in the routes.php file: ...

Steps for initiating a $.ajax POST request from a client to a server

Currently, I am working on a phonegap application where I need to transfer some data from an HTML file to a server and receive a response in return. Everything works fine when all the files are on the same server. However, once I separate the files between ...

Proper method for executing a synchronous AJAX POST request and subsequently submitting a form

Currently, I have an ASP submit button in my code. <asp:button runat="server" Text="Submit" id="btnSubmitOrder" OnClientClick="return SubmitOrder()" /> The JavaScript function I'm using, SubmitOrder(), is designed to execute a POST request. De ...

Refresh a row in real-time by utilizing a modal with JavaScript or jQuery

Is there a way to dynamically edit and update a previously submitted row (category name) in a table? I am able to edit a row by clicking on an edit button and displaying a modal with the current value. However, I am facing a challenge when trying to submit ...