Tenemos dos matrices de objetos:

Primero:

const allUsers = [
  {
    id: 49,
    name: 'William'
  },
  {
    id: 82,
    name: 'Michael'
  },
]

Segunda:

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]

[PREGUNTA]:

¿Cómo puedo devolver una matriz de todos los usuarios que estuvieron INACTIVOS durante los últimos 3 meses? (De William)

-2
Mihai Ciobanu 20 feb. 2020 a las 14:23

2 respuestas

La mejor respuesta

Puedes probar algo

function monthDiff(dateFrom, dateTo) {
 return dateTo.getMonth() - dateFrom.getMonth() + 
   (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
]

const res = usersWithActivity.filter(user => (monthDiff( new Date(user.last_activity),new Date()) > 3))
1
Harish 21 feb. 2020 a las 05:03

Prueba esto

const allUsers = [
  {
    id: 49,
    name: 'William'
  },
  {
    id: 82,
    name: 'Michael'
  },
];

const usersWithActivity = [
  {
    id: 49,
    name: 'William',
    last_activity: "2019-06-20T12:09:55.000Z"
  },
  {
    id: 82,
    name: 'Michael',
    last_activity: "2020-02-20T11:08:50.000Z"
  }
];

function isInactiveSince(lastActivity, inactiveSince) {
  let la = new Date(lastActivity);
  let s = new Date().setMonth(inactiveSince)
  return la <= s
}

function play () {
    const all = [];
	usersWithActivity.map((ua, i) => {
      if(isInactiveSince(ua.last_activity, -3)) {
        const user = allUsers.find(u => u.id == ua.id)
        all.push(user);
      }
    })
    console.log(all)
}

play()
0
Piyush Patel 20 feb. 2020 a las 11:44