angularangular-materialangular-arrays

Create new array from existing array with specifc node values


I have following array:

[
  {
    fileName: "test.pdf",
    fileUrl: "https://test-url1.com/test.pdf",
    isDeleted: true
  },
  {
    fileName: "test.pdf",
    fileUrl: "https://test-url1.com/test.pdf",
    isDeleted: true
  }
]

Now I need to create new array from this array which will contain only fileUrl data.

So that new array will have only fileUrl node and all it's links.

Should I use map OR filter method, or any other suggestion for this.

Thanks


Solution

  • You should use map for this.

    const urlArray = array.map((item: any) => item.fileUrl);
    
    // [ "https://test-url1.com/test.pdf", "https://test-url1.com/test.pdf"]
    

    The rule of thumb is if you want to change the structure of the array you use map, if you want to get a subset of the array you use filter.