-3

Good day guys! I have encounter some problem. I want to delete all the data from the array but doesn't delete that 1 data based from value.

example:

key = '2' 
array = [ 
         'data1': 'foo',
         'data' : 
                 {
                  'id' : '1', 
                  'id' : '2', 
                  'id' : '3'
                 }
         ]

result = [
          'data1': 'foo',
          'data' : 
                  {
                   'id' : '2'
                  }
         ]

that's all thank you

  • You can use `filter` method to do so. Please search on google before doing any type of questions. – Sifat Haque Jun 09 '19 at 16:03
  • 1
    Possible duplicate of [How can I only keep items of an array that match a certain condition?](https://stackoverflow.com/questions/27131984/how-can-i-only-keep-items-of-an-array-that-match-a-certain-condition) – Nick is tired Jun 09 '19 at 16:05

2 Answers2

2

You can use filter() and compare the value with key.

const key = 'foo';  
const array = ['foo', 'box', 'tree', 'bar'];
const result = array.filter(x => x === key);
console.log(result)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

the simplest way will be to reassign the array or create a new array with the result

const key = 'foo';
let array = ['foo', 'box', 'tree', 'bar'];
/*array = new Array(key); //be carefull if yoy are using this and the key is singular numeric value*/
array = [key];
console.log(array);
saurabh
  • 2,553
  • 2
  • 21
  • 28