简体   繁体   中英

How would one add items to the beginning of an array with Lodash?

I've been searching for a while to add items to the beginning of an array with lodash. Unfortunately I can't seem to find anything other than lodash concat (to the end of the array) . The docs don't seem to say anything about it either.

I got the following code:

const [collection, setCollection] = useState({
  foo: [1, 2, 3]
});

const addToCollection = (key, items) => {
  setCollection(prevCollection => ({
   ...prevCollection,
   [key]: _.concat(prevCollection[key] || [], items)
  }));
};

But this concats all the items to the end. I don't want to sort them every time because that uses unnessecary processing power, I would much rather just add them to the beginning because the API always pushes the items already sorted

How would I accomplish this:

addToCollection('foo', [4, 5, 6]);
console.log(collection['foo']) // [4, 5, 6, 1, 2, 3];

Instead of what is happening now:

addToCollection('foo', [4, 5, 6]);
console.log(collection['foo']) // [1, 2, 3, 4, 5, 6];

Try swapping the arguments:

_.concat(items, prevCollection[key] || [])

Or vanilla JS is pretty easy too:

Collection.unshift('addMe', var, 'otherString' )

https://www.w3schools.com/jsref/jsref_unshift.asp#:~:text=The%20unshift()%20method%20adds,use%20the%20push()%20method .

I know you asked for lodash but I figured this is a good thing to be aware of too:)

EDIT:

To clarify, this works the same whether you're pushing defined vars, string, arrays, objects or whatever:

let yourArray = [1,2,3];
let pushArray = [1,2,3,4];
let anotherArray = [7,8,9];
yourArray.unshift(pushArray, anotherArray);

will push "pushArray" and "anotherArray" to the begining of "yourArray" so it's values will look like this:

[[1,2,3,4], [7,8,9], 1,2,3]

Happy Coding!

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