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

Exploring, navigating, and cycling through JSON in Node.js

I'm currently attempting to extract the titles of front page articles from Reddit's RSS feed and running into some issues. Below is the snippet of code I am working with: //var util = require('util'); //var cheerio = require('chee ...

Creating immersive visualizations using Three.js and WebGL, as well as leveraging 2D canvas for rendering graphics, involves passing the getImageData

Recently diving into WebGL (and 3D graphics in general) using three.js, I'm looking to create multiple textures from a 2D canvas for rendering various meshes, each with its own unique texture. Simply passing the canvas to a new THREE.Texture() causes ...

Python string manipulation to create a list from text

I've got a bunch of JSON objects that are all smashed together in a single string. jsonString = "[{'key1':'value1','key2':'value2'}, {'key1':'value1','key2':'value2',&ap ...

How can I deactivate the main color of the FormLabel when the focus is on the radio button group?

Is there a way to change the color of FormLabel to black instead of the primary color when the radio button group is focused? const styles = { formLabel: { color: "#000" }, formLabelFocused: { color: "#000" } }; function App({ classes } ...

The jQuery autocomplete feature presents all choices regardless of what is typed into the input field

I'm currently working on a jQuery script that retrieves a JSON response and creates individual "player" objects based on the data received. These player objects are then added to the availablePlayers array, which serves as the data source for the aut ...

Clicking on the parent div with a Jquery onclick event does not trigger when the child image is clicked

I'm running into an issue with a simple code containing an image within a div Oddly enough, clicking on the div itself (even with padding) triggers the function, but clicking directly on the image does not. $(".parent0").click(function() { conso ...

What is the best way to implement sorting in a table using react virtualized?

I've been working on implementing sorting in my project using the table sorting demo available on Github. Here is the code I'm using: import React from 'react'; import PropTypes from 'prop-types'; import { Table, Column, Sor ...

MySQL field being updated upon page unload

I'm currently developing a Content Management System (CMS) that allows users to access and organize records within a MySQL database. One of the features I have implemented is a user login system for the CMS. As part of this project, I am working on in ...

What is the best method for converting Unix time to a readable date

<el-table-column label="Time Created" prop="create_time"></el-table-column> https://i.stack.imgur.com/aoLjf.png The timestamp data from the backend is in milliseconds format (e.g. 1527150668419) and is stored as create_time property in this.i ...

Troubleshooting steps for resolving a node.js error during execution

I recently delved into server side programming with node.js, but I'm encountering some issues when trying to execute it. My server is set up at 127.0.0.1:80, however, I keep running into errors. Console: Server running at http://127.0.0.1:80/ node:ev ...

Uncovering hidden links in a menu with Python Selenium and JavaScript

Can someone provide guidance on how to activate the JavaScript submenu associated with this button, "x-auto-54"? <table id="x-auto-54" class=" x-btn avtar-x-btn x-component x-btn-noicon x-unselectable " cellspacing="0" role="prese ...

Display the flowplayer div when the anchor is clicked

I have a dynamic CGI page that displays a list of files. The number of files varies based on uploaded content, so I am looking to create previews for video files. Below is a snippet of HTML code: <TMPL_LOOP files> <tr> <td&g ...

Trouble encountered in PHP: Generating a file from POST data and initiating download prompt for the user not functioning as intended

On my webpage, users fill out forms and input fields, which are then sent to a PHP page via Ajax and $_POST. The PHP file successfully writes the output to a txt file. However, I'm facing an issue trying to prompt the user to download the file on the ...

Submitting information retrieved through an AJAX request to a MySQL database using PHP

I have implemented a JavaScript function to collect and display data, but now I am looking to save this data into a MySQL database for tracking purposes. I attempted to connect to the MySQL database locally using PHP code, but encountered some issues. I be ...

What is preventing me from returning the result of $.ajax, but I can return the result of $http.post?

I am facing an issue with having 2 return statements in my code: return $http.post({ url: CHEAPWATCHER.config.domain + 'api/Authenticate', contentType: 'application/x-www-form-urlencoded; charset=UTF-8', data: data }); re ...

Show picture in web browser without the file extension

Is there a way to display an image in the browser without the file extension, similar to how Google and Unsplash do it? For example: Or like this: ...

Advantages and disadvantages of distinct methods for looping through HTML elements

My JS code generates HTML elements that are structured like this: <div id="container"> <div id="block_1" class="blocks"></div> <div id="block_2" class="blocks"></div> <div id="block_3" class="blocks"></di ...

What is the reason for the unique behavior of v-bind with boolean attributes? More specifically, why is the number 0 considered truthy in

According to the official documentation, <button v-bind:disabled="isButtonDisabled">Button</button> In this example, the disabled attribute will be added if isButtonDisabled is equal to 0, despite the fact that in JavaScript, 0 is co ...

I have a large array with multiple elements that I need to search through a file. I want to only print out the array elements that are not already present in the file, ensuring that there are

Seeking assistance for the following code: I am working with an array containing 155 elements and a file that contains some elements of the array. I need to retrieve all values of the array elements that are present in the file. In cases where the array e ...

Manipulating data with Entity Framework using Knockout and AngularJS

When creating a knockout restful service, the first attempt was successful. However, upon implementing it in Angular, there were issues with the database displaying an ID with other fields labeled as undefined. Trying to fix this, I recreated the WCF Servi ...