-3

I want to remove an element from the array by key. However, I have an array quite different from the most.

array1 = [ { ny:    { gt:0 }}
         , { roma:  { gt:0 }}
         , { paris: { gt:0 }} 
         ]

If I want to remove the one with roma, how should I do it?

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
mytoto
  • 15
  • 6
  • 2
    It would be nice if you could should any research you've done on the subject, and any attempts you've made to solve the problem yourself. – Heretic Monkey Aug 31 '20 at 14:36
  • 1
    Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Aug 31 '20 at 14:39

2 Answers2

2

You can filter your array based on the keys of each Object that it contains. In your case, you are looking to filter out the Object whose keys contains the string "roma":

const filtered = array1.filter(item => !Object.keys(item).includes('roma'));
ajm
  • 19,795
  • 3
  • 32
  • 37
0

You can splice the value after you find its index. This will remove it in-place.

const removeFromArray = (arr, key) => {
  const index = arr.findIndex(item => Object.keys(item).pop() === key);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
};

const array1 = [
  { ny    : { gt: 0 } },
  { roma  : { gt: 0 } },
  { paris : { gt: 0 } }
];

console.log(removeFromArray(array1, 'roma'));
.as-console-wrapper { top: 0; max-height: 100% !important; }

If you do not want to modify it, filter the array.

const removeFromArray = (arr, key) =>
  arr.filter(item => Object.keys(item).pop() !== key);

const array1 = [
  { ny    : { gt: 0 } },
  { roma  : { gt: 0 } },
  { paris : { gt: 0 } }
];

console.log(removeFromArray(array1, 'roma'));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132