简体   繁体   中英

Remove the specific object from array and shift this object on 0 index of the same array

I have an array which has multiple objects. I just want to remove a object by using comparing the title and shift this object on 0 index at the same array. How can I do it. Please suggest me the solution.

Input Array:

 const inputArr = [{id:1, title:"John",age:20},{id:2, title:"smith",age:22},{id:3, title:"stokes",age:24},{id:4, title:"david",age:30},{id:5, title:"William",age:28},{id:6, title:"Andy",age:32}]

Output Array:

const outputArr = [{id:5, title:"William",age:28},{id:1, title:"John",age:20},{id:2, title:"smith",age:22},{id:3, title:"stokes",age:24},{id:4, title:"david",age:30},{id:6, title:"Andy",age:32}]

Remove the object with title===William from array and shift into the 0 index

you can simply use sort for that

 const inputArr = [{id:1, title:"John",age:20},{id:2, title:"smith",age:22},{id:3, title:"stokes",age:24},{id:4, title:"david",age:30},{id:5, title:"William",age:28},{id:6, title:"Andy",age:32}] const outputArray = [...inputArr].sort((a, b) => { if(a.title === 'William') return -1 if(b.title === 'William') return 1 return a.id - b.id }) console.log(outputArray)

 const inputArr = [{id:1, title:"John",age:20},{id:2, title:"smith",age:22},{id:3, title:"stokes",age:24},{id:4, title:"david",age:30},{id:5, title:"William",age:28},{id:6, title:"Andy",age:32}]; // `findIndex` of the appropriate object const index = inputArr.findIndex(obj => obj.title === 'William'); // `splice` out the object and then `unshift` it // to the start of the array (Note: we don't have // to make any changes if the index is 0) if (index > 0) { inputArr.unshift(inputArr.splice(index, 1)); } console.log(inputArr);

Additional documentation

const inputArr = [{id:1, title:"John",age:20},{id:2, title:"smith",age:22},{id:3, title:"stokes",age:24},{id:4, title:"david",age:30},{id:5, title:"William",age:28},{id:6, title:"Andy",age:32}]
    
    const getTitle = inputArr.filter((item) => item.title === 'William')
    const getRest = inputArr.filter((item) => item.title !== 'William')
    
    
    console.log(getTitle.concat(getRest))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM