Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array of mongoose ObjectIds into an array of strings?

I have an array of ObjectIds like this:

[ 5cd295fbc53f626fd9d70894,
  5cb0624945111f1c5fdf2527,
  5cc290f5b90fc527c1e46efd,
  5cd6737f294e7b6ec3d9420f,
  5cd295fbc53f626fd9d70894,
  5cb0624945111f1c5fdf2527,
  5cc290f5b90fc527c1e46efd,
  5cd6737f294e7b6ec3d9420f,
  5cd295fbc53f626fd9d70894 ]

I need to convert each Objectid into strings.

I have tried toString() and JSON.stringify(). But toString() splits every character into a string and JSON.stringify() does not affect the array.

Actually I was working on finding the unique Ids in the array. I have tried many functions to get unique elements, but they seem to work only with numbers and strings and not ObjectIds.

On finding the type of element, it displayed it as an object.

So I'm trying to convert the array of objects to array of string, so that I can easily use one of the functions to get the unique elements.

Expected output would be like this:

[ "5cd295fbc53f626fd9d70894",
  "5cb0624945111f1c5fdf2527",
  "5cc290f5b90fc527c1e46efd",
  "5cd6737f294e7b6ec3d9420f",
  "5cd295fbc53f626fd9d70894",
  "5cb0624945111f1c5fdf2527",
  "5cc290f5b90fc527c1e46efd",
  "5cd6737f294e7b6ec3d9420f",
  "5cd295fbc53f626fd9d70894" ]
like image 915
Shambhavi_RB Avatar asked Nov 18 '25 09:11

Shambhavi_RB


1 Answers

You could do it with map. Call toString for each element in the array and returning them in a new array as strings.

For example:

const stringsArray = objectIds.map(x => x.toString());

Then the most efficient way to get unique results in an array would be to put them on a Set. So it would look like the following:

const uniqueStrings = [...new Set(stringsArray)];
like image 193
Alvaro Avatar answered Nov 19 '25 22:11

Alvaro