Combine Array Of Strings With String

Viewed 55

I need to combine the LAST fromAddress and toAddresses values into just one set of array without duplication and without the loginUser.

Expected Output

   { "newResponse": ["james@gmail.com", "ken@yahoo.com"] }

const loginUser = "jane@gmail.com"

const old = [
  {
    "toAddresses": ["joker@gmail.com", "jake@gmail.com"],
  },
  { 
    "fromAddress": "ken@yahoo.com",
    "toAddresses": ["jane@gmail.com", "james@gmail.com"],
  }
];

let emailLength = old?.length - 1
let email = old[emailLength]

 

const newResponse = Array.from(new Set([...email.map(x => [...x.toAddresses].concat([...x.fromAddress || []]))])) 
console.log(newResponse)

2 Answers

You're trying to call map on an object, but is only an array method.

You can just access the properties directly on the email object, since you know what you're looking for you don't need to iterate on it.

Then filter the array for the logged in user and construct a new object for the response.

const loginUser = "jane@gmail.com"

const old = [
  {
    "toAddresses": ["joker@gmail.com", "jake@gmail.com"],
  },
  { 
    "fromAddress": "ken@yahoo.com",
    "toAddresses": ["jane@gmail.com", "james@gmail.com"],
  }
];

let emailLength = old?.length - 1
let email = old[emailLength]



let addresses = Array.from(new Set([...email.toAddresses, email.fromAddress]))
addresses = addresses.filter(addy => addy !== loginUser)
const newResponse = { "newResponse": addresses }
console.log(newResponse)

const loginUser = "jane@gmail.com"

const old = [
  {
    "toAddresses": ["joker@gmail.com", "jake@gmail.com"],
  },
  { 
    "fromAddress": "ken@yahoo.com",
    "toAddresses": ["jane@gmail.com", "james@gmail.com"],
  }
];

let last = old[old.length - 1];
let combined = new Set([last.fromAddress, ...last.toAddresses]);
combined.delete(loginUser);
let newResponse = Array.from(combined);
console.log({newResponse});

Related