The insertItemBefore method inserts a new item into the collection immediately before the specified item by its primary key.
If the target item is not found, the new item is appended to the end of the collection.
After insertion, an update event will be triggered.
ℹ️ Details:
- If the target item exists, the new item is inserted directly before it.
- If the target item is not found, the behavior is equivalent to
appendItem.
collectionInstance.insertItemBefore(key, item): boolean;key— the primary key of the item before which the new item should be inserted.item— the item to insert.- Returns —
trueif the item was successfully inserted, otherwisefalse.
- The target item is searched by the provided key.
- The
insert:beforehook is called. - If the target item is found:
- The new item is inserted immediately before it.
- If the target item is not found:
- The new item is appended to the end of the collection (like
appendItem).
- The
insert:afterhook is called. - The
updateevent is triggered.
const collection = new Collection({
initialItems: [
{ key: 'user1', name: 'John Doe' },
{ key: 'user2', name: 'Alice' },
],
});
collection.insertItemBefore('user2', { key: 'user3', name: 'Bob' });
console.log(Array.from(collection));
// [
// { key: 'user1', name: 'John Doe' },
// { key: 'user3', name: 'Bob' },
// { key: 'user2', name: 'Alice' }
// ]const collection = new Collection({
initialItems: [
{ key: 'user1', name: 'John Doe' },
],
});
collection.insertItemBefore('nonexistent', { key: 'user2', name: 'Alice' });
console.log(Array.from(collection));
// [
// { key: 'user1', name: 'John Doe' },
// { key: 'user2', name: 'Alice' }
// ]const collection = new Collection({
primaryKey: 'id',
initialItems: [
{ id: 1, name: 'John Doe' },
],
});
collection.insertItemBefore(1, { id: 2, name: 'Alice' });
console.log(Array.from(collection));
// [
// { id: 2, name: 'Alice' },
// { id: 1, name: 'John Doe' }
// ]