What is the best way to transform an array of objects' key values into their corresponding index values?

I have an array of objects in the following format:

 var values = [
  {
    position: 6,
  },
  {
    position: 4.5,
  },
  {
    position: 2,
  },
  {
    position: 7.5,
  },
  {
    position: 2,
  },
  {
    position: 5,
  },
  {
    position: 3.5,
  },
];

I want to change the key "position" value into the index of the object in the array. If any key value has a .5 decimal, I need to add the value before that index and continue assigning positions to the data above accordingly. The desired output should be as follows:

 var values = [
  {
    level: 1,
  },
  {
    level: 1.5,
  },
  {
    level: 2,
  },
  {
    level: 2.5,
  },
  {
    level: 3,
  },
  {
    level: 4,
  },
  {
    level: 4.5,
  },
];

Below is the code written to achieve the desired output:

 values = values.map((item, index) => {
  return {
    level: index + 1 - (item.position % 1 === 0.5 ? 0.5 : 0),
  };
});


OUTPUT :- [{"level":1},{"level":1.5},{"level":3},{"level":3.5},{"level":5},{"level":6},{"level":6.5}]

However, the current implementation is not yielding the expected results.

Your assistance on this matter would be greatly appreciated.

Thank you in advance!

Answer №1

In order to update the key for each iteration, it is important to keep track of the last key value:

const values=[{position:6,},{position:4.5,},{position:2,},{position:7.5,},{position:2,},{position:5,},{position:3.5,},];

const results = [];

let previousKey = 0;

for (const object of values) {
    if (object.position % 1 !== 0) previousKey += 0.5;
    else previousKey = Math.floor(previousKey + 1);
    
    results.push({ key: previousKey });
}

console.log(results);

If the position in the object is not a whole number (checked using % 1), we increment by 0.5. If it is a whole number, we simply add 1 to the key after ensuring that it is floored to avoid getting floating point keys unintentionally (e.g., floor(2.5 + 1) = 3).

Answer №2

A straightforward approach is to utilize a for loop that maintains the previous level in memory.

let arr=[{posi:6},{posi:4.5},{posi:2},{posi:7.5},{posi:2},{posi:5},{posi:3.5},];
let res = [], prev = 0;
for (const {posi} of arr) {
  const level = prev + (posi % 1 === 0 ? 1 : .5);
  res.push({level});
  prev = Math.floor(level);
}
console.log(res);

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

What is the best practice for using templates in a constructor versus connectedCallback?

Should I apply template in the constructor or connectedCallback of a custom element? In my experience, when I apply it in connectedCallback, sometimes attributeChangedCallback is called before and I can't query for elements. export class TestElement ...

Mysterious attributes of angular 6's <table mat-table> tag

This particular question regarding the angular material table has not been duplicated in any other discussions. Other similar questions pertain to angular versions 2-5, not version 6 The issue I am encountering is as follows: Can't bind to 'dat ...

Unable to Retrieve Modified Content with $().text();

In the process of developing an app, I am encountering a challenge where I need to transfer user input to another element after processing it. However, I am facing an issue with accessing the updated value of the <textarea> using .text(), as it only ...

The Angular Service code cannot be accessed

Currently, I am utilizing Local Storage in an Angular 5 Service by referencing https://github.com/cyrilletuzi/angular-async-local-storage. My goal is to retrieve data from storage initially. In case the value is not present, I intend to fetch data from fir ...

Navigating session discrepancies: Combining various social media platforms using Next.js and NextAuth

Recently, I ran into a problem where, upon logging in with Google, I found myself needing access tokens for Twitter and LinkedIn to send out API requests. The issue came about when NextAuth modified my session data to be from either Twitter or LinkedIn ins ...

Stop the webpage from scrolling when clicking on a ui-grid field

Is there a way to prevent page scrolling when clicking on a row field in ui-grid? I'm working with a page that has ui-grid, and each row includes an anchor tag with a URL value linked and target="_blank" to open in a new tab like the example below: ...

`'download as' feature using JavaScript and PHP`

I have implemented a JavaScript function on my website that, with the help of a PHP function, creates a file locally on the server in the same directory as the website files. The file name is only known to these JavaScript and PHP functions. Now, I am look ...

What is stopping me from using redux's connect function with material-ui's withStyles?

Having an issue with adding the withStyles() hook from material-ui to a redux container-component using the connect() function through the compose function from 'recompose'. I keep getting this error from the recompose package: TypeError: Functi ...

Can JQuery be used to identify the CSS styles applied to selected elements?

Highlight the text by selecting it and clicking a button. If the text is already highlighted, clicking the button should make the selected text return to normal. Can this be achieved using jQuery and a single button? Is it possible to identify the CSS st ...

Innovative technique for dynamically retrieving JavaScript data

I am facing an issue with my code snippet. The original code looks like this: var dataSet = [ [ "Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800" ], [ " ...

The error message "domElement" cannot be modified because it is read-only in the THREE.WebGLRenderer

I encountered an issue while attempting to initialize the WebGLRenderer: (Some unnecessary lines have been omitted) import * as THREE from "https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48544e5 ...

Pause and anticipate the subscription within the corresponding function

Is there a way to make an If-Else branch wait for all REST calls to finish, even if the Else side has no REST calls? Let's take a look at this scenario: createNewList(oldList: any[]) { const newList = []; oldList.forEach(element => { if (eleme ...

Reposition the chosen item from the menu to the top spot

I currently have a top navigation bar with various menu items. $('.subpage_top_nav li').click(function(e) { e.preventDefault(); $(this).parent().prepend(this); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery. ...

Changing the texture on a material in three.js

I have successfully set up a texture on a mesh using three.js, and it initially loads exactly as I want it to: texture = THREE.ImageUtils.loadTexture("textures/hash.png"); texture.needsUpdate = true; uniforms = { colo ...

Guide to changing base 64 into a byte Array

Struggling to convert base64 to byte Array in Angular. Attempted solutions have not been successful. // Handling file upload handleUpload(event) { if (event.target.files[0]) { this.file = event.target.files[0].name; } const file = event.targ ...

Modifying a table row in real-time with the power of JQuery/JavaScript

I successfully created a table with a for loop in Java Spring and now I'm trying to dynamically show and hide specific parts of it when a button is clicked. Here's a simplified version of what I have: <jsp:attribute name= "scripts"> ...

PHP Javascript/CSS Organization Tool (similar to Haste or Juicer)

Check out this video on Facebook's use of Haste, a CSS and Javascript packaging tool: http://www.facebook.com/video/video.php?v=596368660334 If you're interested in tools like Haste, Juicer might be worth looking into. It's a similar tool d ...

I'm puzzled as to why my set-cookie disappears after I make a subsequent request

Issue arises when logging in through an endpoint results in a response header with a http-only cookie. However, subsequent requests to other endpoints do not include the set-cookie in the headers. Attempts have been made to resolve this problem. The follo ...

Extract the string values of a specific property from an array of objects using Typescript

I'm currently working on a project where I need to ensure type safety, but I'm unsure if it's achievable: Suppose I have an array of "services", with each service defined as follows: interface Service { id: string; dependencies?: [strin ...

NVDA fails to announce the "dialog" when a Modal is launched

When testing this simple modal example, I noticed that although the role is set to dialog and focus is correctly received on the dialog container when it opens, NVDA fails to announce the word 'dialog' at the beginning. This issue has been report ...