Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how:

Starting with this

[
    {name: "test", place: "country"},
    {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"},
    {name: "test2", place: "Europe"}
]

You can achieve the following

[
    {name: "test", place: "country"},
    {name: "test2", place: "Europe"}
]
[
    {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}
]

Answer №1

If you consider objects to be equal when they have the same properties, one way to handle this is by storing keys as stringified indices in a collection object and then checking if a properties-key already exists:

var arrcoll = {};
function add(o){
    var keys = JSON.stringify(Object.keys(o).sort());
    var arr = arrcoll[keys];
    if(arr)
        arr.push(o);
    else
        arrcoll[keys] = [o];
    return arr;
}

This process can be implemented dynamically or on an existing array, as demonstrated in this Fiddle

Answer №2

Imagine you have a collection of objects with various attributes like this:

var entities = [
    { name: 'Seymour Skinner', role: 'Principal' },
    { name: 'Kwik-E-Mart', lat: 23, long: 100 },
    { name: 'Sideshow Bob', role: 'Comic Foil' },
    { name: 'Flaming Tyre Yard', lat: 12, long: 88 },
    { name: 'Joe Quimby', role: 'Mayor' }
];

If you wish to group them into separate lists as shown below:

locations = [
    { name: 'Kwik-E-Mart', lat: 23, long: 100 },
    { name: 'Flaming Tyre Yard', lat: 12, long: 88 }
];

characters = [
    { name: 'Seymour Skinner', role: 'Principal' },
    { name: 'Sideshow Bob', role: 'Comic Foil' },
    { name: 'Joe Quimby', role: 'Mayor' }
];

You can achieve this using the built-in Array.filter method as demonstrated in the code snippet below:

var locations = entities.filter(function(entity) {
    if (entity.role !== undefined) {
        // it is a character since locations do not have roles
        return true;
    } else {
        return false;
    }
});

var characters = entities.filter(function(entity) {
    if (entity.lat !== undefined && entity.long !== undefined) {
        // it is a location since characters do not have coordinates
        return true;
    } else {
        return false;
    }
});

Answer №3

Javascript Objects are versatile entities, allowing for flexibility and adaptability throughout program execution as they exhibit dynamic characteristics.

JavaScript stands out as a loosely typed or dynamic language. This signifies that there is no need to specify the type of a variable in advance. The determination of the variable type occurs automatically during program processing. Consequently, it is possible to have the same variable with different types:

var anything = arrayOfAnyOtherType[0]; 

This approach remains valid... By iterating through your source array and filling it, each object can be given specific behaviors.

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

Having issues with ng-model in AngularJS functionality

Having trouble updating a parent scope within a nested ng-repeat loop. I've been stuck on this issue for the past couple of hours! Here is my nested loop: <div ng-repeat="input in config" style="border: 1px solid #000;"> <div ng-repeat= ...

How to effectively leverage useMediaQuery in material ui?

Upon completing the web application, I have made the decision to ensure it is mobile-friendly. Utilizing the material UI framework with react, I delved into the documentation but found myself uncertain about how to effectively implement it. Let me provide ...

Working with json, lists, and dictionaries in Python

Apologies for the extensive content, but I wanted to provide all necessary details. I am in the process of extracting specific data points from a JSON file with the following structure: { "count": 394, "status": "ok", "data": [ { ...

Tips for preventing a table from showing up while scrolling unnecessarily when utilizing a heading with the CSS position property set to 'sticky'

Currently, I am facing an issue with creating a sticky header for my table. The problem arises when the header of the table has rounded edges (top right and top left) along with a box-shadow applied to the entire table. As the user scrolls through the tabl ...

What is the reason for Backbone including model details within {model: {model_property: value,...}} when saving a model?

I am currently developing an application using node.js and backbone.js. However, I have encountered an issue where saving a model results in the JSON being nested inside a model dictionary. node = new NodeModel({prop1:"value1", prop2:"value2"}); node.save ...

Why is the Angular directive '=&' value binding to the scope showing as undefined?

An Angular directive has been defined within my application: (function() { 'use strict'; angular .module('almonds') .directive('security', ['$animate', 'AuthFactory', directive]); fun ...

Capture element in Javascript with screenshot functionality

I've been trying to save an image on my local website, but most of the code examples I find are for C# and Java, which I am struggling to convert to JavaScript. Many of the examples I come across use libraries like Point and IO that are not available ...

Obtain an array containing only the specific values of each object

Currently, I have the following code snippet: <db.collection>.find({ id : { $exists: true } }) This query retrieves all documents containing an id property. However, I am interested in transforming this result into an array that contains only the va ...

There are no documents found with the specified UUID in MongoDB

I have been attempting to retrieve a specific document from MongoDB that includes the field "ownerId" containing a binary UUID. In the Mongo console, when I run the command db.dataset.find({ownerId: BinData(3,"ZQ6EAOKbQdSnFkRmVUUAAA==")}).pretty() The ou ...

Troubleshooting JQuery Variable Overwriting Problem

Here is the code snippet I am working with: <script> $(document).ready(function() { var settings_image ={ url:"<?php echo site_url('/cms/editor/upload/images');?>", method: "POST", fileName: "file", returnType: ...

Struggling to make a form submit work with AngularJS and a Bootstrap datetime picker

Struggling to create a post and include name and datetime using a bootstrap datetimepicker. After selecting the datetime and clicking add, nothing happens. However, if I manually type in the field and click add, it submits successfully. Despite reading up ...

Unexpected behavior observed when implementing form-based authentication with AngularJS on Websphere platform

Currently, I am tackling a project in AngularJS that involves form-based authentication. However, I am facing some unexpected behavior that is proving to be quite elusive to track down. The application is hosted on Websphere 8.0.0.10, and session manageme ...

Data is being stored in a fresh record rather than being saved within an array

I'm currently working with the MEAN stack and using the Multer module for uploading images. While I am able to successfully retrieve images from Angular and post image paths to a Mongoose collection, I am encountering an issue. Instead of receiving ...

How to ensure a div within an anchor tag occupies the full width in HTML and CSS?

In my code, I am working on creating multiple small boxes with images and centered text inside. The goal is to have these boxes clickable, where clicking the image will take you to a specific link. On desktop, I want a hover effect that darkens the image b ...

Harnessing the Power of Google Apps Scripts: Mastering the Art of Handling Comma-Separated Spreadsheet Values Transformed

I have a spreadsheet where column 1 contains source file IDs, with each cell holding only one ID. Column 2 has destination file IDs, where cells contain multiple IDs separated by commas. I utilize a script to retrieve these values and perform various opera ...

Guidelines for creating an auto-scrolling React Native FlatList similar to a Marquee

I currently have a FlatList component set up in my project. <FlatList horizontal data={data} key={(item, index) => index.toString()} ListHeaderComponent={listHeader} renderItem={ // renderin ...

Angular, choose, establish a default option

Despite my attempts, I am struggling to set the default option for a select element using AngularJS. My Technologies: AngularJS, Angular-UI-router, Bootstrap Key HTML snippet: <select ng-model="selectedCompany" ng-options="c.name for c in companies" ...

What is the method to determine the inviter on Discord.js?

Hi there! I'm currently working on an Invite Logger and could use some assistance. I'm having trouble figuring out how to identify the user who invited another user. client.on('guildMemberAdd', async (member) => { const channel = ...

Transferring event arguments to JavaScript in ASP.NET C# through OnClientClick

Currently, I have an asp button on my webpage. In the code behind within the Page_Load method, I am assigning some JavaScript calls in the following manner. btnExample.OnClientClicking = "functionOne(1,2);"+"function2()"; However, I am encountering a pro ...

The directive does not actively monitor changes to the value attribute

Whenever I click on an input field, a color picker pops up and the selected RGBA string is written back to the input's value attribute. Initially, I believed that adding ng-model="color" to the input tag would be enough for the color variable to hold ...