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
CodePudding user response:
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)
CodePudding user response:
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
CodePudding user response:
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))