Home > database >  create a new Array with filtered out props
create a new Array with filtered out props

Time:09-28

I have been trying to filter an Array by its props and not by its value so my original array would be -

const orignalArray =[
{id: 1, name:"jim", email:"[email protected]",age:20},
{id: 1, name:"jom", email:"[email protected]",age:30}
]

id like to be able to use (n) amount of filters. My output array would look ideally look like this

const filterList["id","age"]
const newArray=[{name:"jim", email:"[email protected]"},{ name:"jom", email:"[email protected]"}]

I have tried to use filter() but cant seem to get it to work.

any help is much appreciated.

CodePudding user response:

In this case you aren't filtering the array rather creating a new one based on the original with derived elements from each. To achieve this you can use the array map function to loop over the array and create a new one with new objects without the desired properties, e.g.:

function removeArrayElementProps(arr, propsToRemove) {
  return arr.map((element) => {
    // Create a copy of the original element to avoid modifying the original
    const newElement = {...element};

    // Remove the desired properties from the new element
    propsToRemove.forEach((propToRemove) => {
      delete newElement[propToRemove];
    });

    // Returning the modified element in map puts it in thew new arry
    return newElement;
  });
}

Then you simply call:

const newArr = removeArrayElementProps(orignalArray, ['id','age']);

This loops over the array, creates a copy of each element, and removes the specified properties from the element.

  • Related