0

const token = [
  {"token":"d2r4Z62OTGiPyNmdHTUfny",
  "time":1652767811},
  {"token":"dnl13twkQIqifdvaxp1t6e",
  "time":1652767811},
  {"token":"eDZxQu0FSWm72D2-T1md5X",
  "time":1652767811},
  {"token":"dnl13twkQIqifdvaxp1t6e",
  "time":1652767811}]; // Try edit me
  const arr = [];
  for (var i=0; i<=token.length-1; i++)
  {
    const millis = Date.now();
    const time  = Math.floor(millis / 1000);
    if (token[i].time > time) {
      arr.push(token[i].token)
    }
   }
   console.log(arr);

between these two token variables are the same, I want to distinguish them from each other, how can I do that? Example Output:

const example = [
  "d2r4Z62OTGiPyNmdHTUfny",
  "eDZxQu0FSWm72D2-T1md5X",
  "dnl13twkQIqifdvaxp1t6e"
];
console.log(example);

3
  • 1
    you mean extracting unique token keys ? what's the purpose of 'time' ? try array.reduce Commented May 17, 2022 at 5:41
  • 1
    Use a Set to eliminate duplicates. Commented May 17, 2022 at 5:42
  • timestamp is not so important Commented May 17, 2022 at 5:45

2 Answers 2

1

Just use a Set as it doesn't allow for duplicates:

const tokens = [
  {"token":"d2r4Z62OTGiPyNmdHTUfny", "time":1652767811},
  {"token":"dnl13twkQIqifdvaxp1t6e", "time":1652767811},
  {"token":"eDZxQu0FSWm72D2-T1md5X", "time":1652767811},
  {"token":"dnl13twkQIqifdvaxp1t6e", "time":1652767811}
];

const now = Math.floor(Date.now() / 1000);
const result = new Set(
  tokens.filter(({ time }) => time > now).map(({ token }) => token)
);

console.log(...result);

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

Comments

1

The easiest way with your current logic is that you can use includes to check token with the arr results. If it's in arr, we don't need to push it to arr.

const token = [
  {"token":"d2r4Z62OTGiPyNmdHTUfny",
  "time":1652767811},
  {"token":"dnl13twkQIqifdvaxp1t6e",
  "time":1652767811},
  {"token":"eDZxQu0FSWm72D2-T1md5X",
  "time":1652767811},
  {"token":"dnl13twkQIqifdvaxp1t6e",
  "time":1652767811}];
  const arr = [];
  for (var i=0; i<=token.length-1; i++)
  {
    const millis = Date.now();
    const time  = Math.floor(millis / 1000);
    if (!arr.includes(token[i].token) && token[i].time > time) {
      arr.push(token[i].token)
    }
   }
   console.log(arr);

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.