learningMonk
learningMonk

Reputation: 1401

how to get the deleted item value using javascript

I have removed an element from an array. Now, I need to display which item is deleted and the remaining items, but have been unsuccessful. Suppose, the array looks like:

let person = ['Cercei','Snow','Arya','Sansa'] 

I have removed 'Snow' and 'Cercei'. So, I need to display two things into two different new array.

delPerson = ['Cercei','Snow'] 
remArray = ['Arya','Sansa']

How can this be done with JavaScript? In my application, I have delete icon with each and every name so i can remove any name. I want to get the deleted name and remaining name into two different array. Please help me how to do that using javascript or lodash

let me tell you my application code:

let person = personData.map(n => n.name) 
let remPerson = person.filter(p => person.indexOf(p) !== -1)

Now, person and remPerson array is showing same value. While comparing the length it is creating the problem.

Upvotes: 0

Views: 279

Answers (3)

Umair Sarfraz
Umair Sarfraz

Reputation: 6079

One way could be to use Array.reduce.

const persons = ['Cercei', 'Snow', 'Arya', 'Sansa'];

const {
  deleted,
  kept
} = persons.reduce((acc, person) => {
  // Note: The deletion condition may vary
  if (person === 'Cercei' || person === 'Snow') {
    acc.deleted.push(person);
  } else {
    acc.kept.push(person);
  }

  return acc;
}, {
  deleted: [],
  kept: []
});

console.log(deleted);
console.log(kept);

Upvotes: 1

Mike
Mike

Reputation: 1337

You can remove items using splice and also keep track of two separate arrays:

let personData  = [{name:'Cercei'},{name:'Snow'},{name:'Arya'},{name:'Sansa'}];
let person      = personData.map(n=>n.name);
let removeItems = ['Cercei','Snow'];
let delPerson   = [];

removeItems.forEach(item=>{
  delPerson.push( 
    ...person.splice( person.indexOf(item), 1 )
  )
});

console.log('delPerson: ', delPerson);
console.log('remaining: ', person);

Upvotes: 0

j3py
j3py

Reputation: 1267

You can use splice, but this will modify your original array. It is unclear to me if that will be ok in the OP's case. Here's Mozilla's documentation on splice: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

let person = ['Cercei','Snow','Arya','Sansa'];

let delPerson = person.splice(0, 2);

console.log(delPerson);
console.log(person);

Upvotes: 0

Related Questions