简体   繁体   中英

Move objects by object fields inside array JavaScript

I have an array of objects, that represents data from a chart. I also have a varibale Timezone. How do I move objects that have sales > 0 according to the Timezone variable? So if Timezone = -5, all objects that have sales > 0 should move it's position -5 indexes. The numbering of the name field should remain intact, from 12 to 1 and from 1 to 11, but sales move according to the Timezone variable. 在此处输入图像描述

You can do next:

  1. Create new array: const result = new Array(yourObjectsArr.length);
  2. Go through yourObjectsArr first time:
yourObjectsArr.forEach((obj, key) => {
  if (obj.sales > 0) {
    // what if (key - timeZone) is negative?
    const result[key - timeZone] = obj;
  }
});
  1. Go through yourObjectsArr second time and deal with all cases when sales <= 0. Mb it'd possible to do it in one loop, depends on which position should occupied these objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM