0

i have obj of array

var data = [{
    value: 1,
    t: 1487203500000
}, {
    value: 2,
    t: 1487213700000
}];

here, i need to compare t obj at inside a loop, if it is exceeds 5 mins, then i need to create a one item with value of null and append into that array.

Expected result will be

var data = [{
    value: 1,
    t: 1487203500000
}, {
    value: null,
    t: null
} {
    value: 2,
    t: 1487213700000
}];

while appending i need to push into same index and existing value should be readjusted.

5
  • Look at: stackoverflow.com/questions/917904/… Commented Feb 24, 2017 at 5:55
  • Or here: stackoverflow.com/questions/1168807/… Commented Feb 24, 2017 at 5:55
  • What exactly if it is exceeds 5 mins means for you? What do you want to compare your data[0]["t"] to? Because obviously all of them exceed 5minutes (by years). Do you want to compare one item to the next, like data[1]["t"] - data[0]["t"] > 5 * 60 * 1000, and if so, insert the null object between them, so data[1] becomes data[2]? Commented Feb 24, 2017 at 6:35
  • @wscourge, yes same expectation only, it should change from data[1] to data[2] nd comparing by t Commented Feb 24, 2017 at 7:23
  • I dont understand your comment since nd comparing by t. Could you please explain what exactly does if it is exceeds 5 mins mean? Commented Feb 24, 2017 at 7:30

1 Answer 1

1

You can use array.splice() for this

The splice() method adds/removes items to/from an array.

var data = [{
    value: 1,
    t: 1487203500000
}, {
    value: 2,
    t: 1487213700000
}];

//  put your index here
//          v
data.splice(1, 0, {value: null, t: null});

console.log(JSON.stringify(data, 0, 8));

In this code

data.splice(1, 0, {value: null, t: null});

1st Parameter (1) -> indicates the position where you want to insert.
2nd Parameter (0) -> indicates how many elements you want to remove.
3rd Parameter ({obj}) -> is the object which we want to insert at position 1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.