(javascript object) if the next values greater of first value by 1 add the values in new object, if not, ignore the values

  Kiến thức lập trình

I have an object and a variable that represents 1 as a value. It can be more, for example: 1,2,3,4,5.....etc.

What I want is to compare the following values with the first value in the object, and if the result of subtracting the first value is greater than or equal to 1, add these values to a new object.
For example:
The first value is 10. The next value is 10.5, which is the largest of 10. We subtract 10 from 10.5. The result is 0.5. This result is less than 1, so we ignore it.

We move to the next value, which is 11, and since 11 is greater than 10.5, we subtract 10 from 11 and not 10.5 from 11. The result is 1, we add it in the new object, and the result is like this: {pr:10, pr:11}.

We move to the next value, which is 11.3, and since 11.3 is greater than 11, we subtract 10from 11.3. The result is 1.3, and now we add it to the new object, and the result is like this: {pr:10, pr:11, pr:11.3}.

We move to the next value, which is 12, which is larger than the previous value, 11.3. we subtract 10 from 12. The result is 2, and now we add it to the new object, and the result is like this: {pr:10, pr:11, pr:11.3, pr:12 }.

We move to the next value, which is 11.5, and we notice that this value is smaller than the previous value, 12. Therefore, we do not subtract 11.5 from 10, but from the previous value, which is 12, and the result is 0.5, so we do not add it to the new object.

We move to the next value, which is 12, and since the previous value was not added to the new object, we compare it with the value that was before 11.5, which is 12, and since the values are equal, we do not add anything to the new object.
So the new object remains as it is.{pr:10, pr:11, pr:11.3, pr:12}.

We move to the next value, which is 11, and since 11 is less than 12, we subtract 11 from 12, and the result is 1, so we add 11 to the new object. The result is: {pr:10, pr:11, pr:11.3, pr:12, pr:11}.

I spent a lot of time trying to reach a conclusion but I couldn’t.
Anyone who can help me, I appreciate this, and thanks to everyone.

let lists = [
  { id: "1", price: 10,  },
  { id: "2", price: 10.5 },
  { id: "3", price: 11,  },
  { id: "4", price: 11.3,},
  { id: "5", price: 12,  },
  { id: "6", price: 11.5 },
  { id: "7", price: 12,  },
  { id: "8", price: 11,  },
]
let finalList = [
  { id: "1", price: 10,  },
  { id: "3", price: 11,  },
  { id: "4", price: 11.3,},
  { id: "5", price: 12,  },
  { id: "8", price: 11,  },
]

LEAVE A COMMENT