What are the steps to find the average of a group of numbers that are stored in a nested object within an array?

I have a collection of shapes in an object, each assigned with a specific color:

const shapeDesign = {
      designId: 1,
      shapes: [
        { shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 }},
        { shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 }},
        { shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 }},
        { shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 }}
      ]
    }

In order to calculate the average color values for each design, I aim to achieve the following output:

Design 1: {r: 191.25, g: 191.25, b: 127.5 }

Considering performance efficiency (Big O notation), what is a more optimal approach to solve this issue?

My initial solution was deemed inefficient, presented below:

const computeAverage = (values) => values.reduce((total, current) => total + current, 0) / values.length;

const { shapes } = shapeDesign;

const reds = shapes.map(shape => shape.color.r)
const greens = shapes.map(shape => shape.color.g)
const blues = shapes.map(shape => shape.color.b)

console.log(`Design ${shapeDesign.designId}: {r: ${computeAverage(reds)}, g: ${computeAverage(greens)}, b: ${computeAverage(blues)} }`)

Answer №1

Your algorithm has a time complexity of O(N) due to the reduce method utilized in the code snippet.

const structure = {
      structureId: 2,
      elements: [
        { elementId: 'element-1', properties: { x: 10, y: 20 }},
        { elementId: 'element-2', properties: { x: 30, y: 40 }},
        { elementId: 'element-3', properties: { x: 50, y: 60 }},
        { elementId: 'element-4', properties: { x: -10, y: -20 }}
      ]
    };

const { elements, structureId  } = structure;

const averagePos = elements.reduce((acc, curr) => ({
  posX: acc.posX + curr.properties.x / elements.length,
  posY: acc.posY + curr.properties.y / elements.length
  }), {
  posX: 0, posY: 0
  }
 );

console.log(`Structure ${structureId}: {x: ${averagePos.posX}, y: ${averagePos.posY}`)

Answer №2

Your current approach has a complexity of O(6n), which essentially simplifies to O(n). However, you have the opportunity to optimize this to O(1n) by utilizing a single reduce() call or a for loop.

const design = {
  designId: 1,
  shapes: [
    { shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 } },
    { shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 } },
    { shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 } },
    { shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 } }
  ]
}

const sums = { r: 0, g: 0, b: 0 };
for (const { color: { r, g, b } } of design.shapes) {
  sums.r += r
  sums.g += g;
  sums.b += b;
}

const len = design.shapes.length;
const result = {
  [`Design ${design.designId}`]: {
    r: sums.r / len,
    g: sums.g / len,
    b: sums.b / len
  }
}

console.log(result);

Answer №3

Modify the for loop by integrating the Array.map() segment into the existing average() function

const design = {
      designId: 1,
      shapes: [
        { shapeId: 'basic-square', color: { r: 255, g: 255, b: 255 }},
        { shapeId: 'basic-circle', color: { r: 255, g: 255, b: 255 }},
        { shapeId: 'basic-diamond', color: { r: 255, g: 0, b: 0 }},
        { shapeId: 'basic-rectangle', color: { r: 0, g: 255, b: 0 }}
      ]
    };

//Design 1: {r: 191.25, g: 191.25, b: 127.5 }

function average(color) {
  let result = 0;
  for(let i=0; i<design.shapes.length; i++) {
    result += design.shapes[i].color[color]
  }
  return result / design.shapes.length;
}

console.log(`Design ${design.designId}: {r: ${average('r')}, g: ${average('g')}, b: ${average('b')} }`)

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

Unable to append comment value to camVariable

I need to update the 'comment' item in my selectedDocuments object with a new value. I want to display an input field in a form where the values of the selectedDocuments object are rendered, and upon submitting this input, I want it to be added t ...

Self-Terminating Program

I have been working on implementing a new datatype named HugeInteger in C++ using classes. I am running into an issue where my program abruptly terminates after printing the first number when attempting to create a new HugeInteger object. Strangely, if I c ...

Displaying content in a hidden div on click event

I am part of a volunteer group for prostate cancer awareness and support, and our website features multiple YouTube videos that are embedded. However, the page has been experiencing slow loading times due to the number of videos, despite them being hidden ...

Issue with Vue v-model not updating values of an array when v-for is used

I am a beginner with Vue and I'm exploring the possibilities of v-model. My goal is to create an array of editable names. Below is the code I have been working on: var app = new Vue({ el: '#app', data: { names: ['Josh', ...

Attaching data to Vue model on the fly within a component

Currently, I am working on creating a straightforward form that will allow users to input various types of currency. Below is a link to a fiddle that demonstrates what I am aiming for, although it is not functioning as intended at the moment: https://jsfi ...

Reversing the order of an array

I am working with an array containing n elements and the following methods: last() - returns the last integer of the array first() - returns the first integer of the array size() - returns the length of the array replaceFirst(num) - adds the integer at t ...

Encountering an Assertion Error when attempting to import a custom package in Angular 13

Seeking assistance: I have developed my initial Angular package which offers various services for making HTTP requests to a server and fetching results. Upon importing the service, the webpage ceases to render and displays the following error message: cor ...

I have created a textbox with a button, but I am unsure of how to delete it

var emailFields = document.getElementById('emails'), addLinkButton = document.createElement('a'), fieldTemplate = emailFields.getElementsByTagName('div'), currentFieldCount = fieldTemplate.length, maxFields ...

Delay the execution of @mouseover in Vue: a guide to managing scope

Looking to implement an action only when the user has hovered over a div for at least 1 second. Here's how it's set up: <div @mouseover="trigger"></div> In the script section: data() { return { hovered: false } } m ...

The manner in which sessionStorage or localStorage is shared between different domains

I am looking to persist data across different domains using sessionStorage or localStorage. How can I achieve this? The data needs to be shared between a Vue project and a React project. English is not my strong suit, so I hope you are able to understand ...

Is the text represented in angular translate using the key instead of the value?

I've been diving into the localization section of ng-book and here's my progress so far: 1) I installed angular-translate using bower install 2) I included it in my HTML file using the script tag <script type="text/javascript" src="js/lib/ ...

Create a custom sorting option for an Angular select dropdown menu that is tailored to a specific

<select name="region" id="region" ng-options="id as name for (id, name) in regions[entry.country]" ng-model="entry.region" class="form-control select-styled" required></select> I am looking to implement a filter or custom sort to rearrange th ...

Ways to soften a section of a canvas component?

What is the simplest way to apply a blur effect to a specific portion of my canvas element? I am utilizing the JavaScript 3D Library known as three.js. This library simplifies the use of WebGL. While they offer examples of blur and depth of field effects, ...

Steps to fix the moment-timezone import problem on meteor npm

I've been attempting to integrate the moment-timezone npm package into my meteor app without success. While the atmosphere package works smoothly, I prefer to use the npm package since the atmosphere one is no longer being updated. I have completely r ...

What is the best way to transfer information between different pages in an HTML document?

I am facing a specific requirement where I must transfer form data from one HTML page to another HTML page. The process involves a total of 5 pages, with the user entering data in the following order: 1st page: Name 2nd page: Weight 3rd page: Height 4t ...

What is the best way to update the content of a div when it is being hovered over?

On my website I am building, there is a division that contains text. When I hover over the division, I want the text to change from "example" to "whatever". I came across a forum discussing this, but I'm having trouble understanding it. Can someone p ...

Enhancing Nativescript elements with pseudo selectors

Is there a way to apply the button:hover effect in Nativescript Buttons? I attempted the following code: Button:highlighted{ background-color: red; } Button:hover{ background-color: red; } Button:touch{ background-color: red; } ...

Exploring MongoDB: executing find and findOne queries while utilizing nested array filtering

This task ended up being more challenging than I initially anticipated. Imagine a simple Posts collection where I need to display all posts along with only the comments that have not been deleted. In other words, how can I filter out deleted comments fro ...

Ways to elegantly re-establish a websocket connection?

I've been working on a single-page application that utilizes HTTP and Websockets. When the user submits a form, I start streaming a response back to the client. Here's a snippet of the client-side code: var html = `<!DOCTYPE html> <met ...

Error message "ValueError: The truth value of an array with more than one element is ambiguous. Please use either a.any() or a.all() when trying to calculate the median of a

I am trying to calculate the median of an array of masked values. I have no trouble computing the mean, but I keep encountering an error when attempting to find the median and I'm unsure of the reason behind it: ValueError: The truth value of an array ...