简体   繁体   English

如何使用 Lodash 将项目添加到数组的开头?

[英]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.我一直在寻找一段时间来使用 lodash 将项目添加到数组的开头。 Unfortunately I can't seem to find anything other than lodash concat (to the end of the array) .不幸的是,除了 lodash concat (to the end)之外,我似乎找不到任何东西。 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我不想每次都对它们进行排序,因为这会使用不必要的处理能力,我宁愿将它们添加到开头,因为 API 总是推送已经排序的项目

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:尝试交换 arguments:

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

Or vanilla JS is pretty easy too:或者 vanilla JS 也很简单:

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

https://www.w3schools.com/jsref/jsref_unshift.asp#:~:text=The%20unshift()%20method%20adds,use%20the%20push()%20method . https://www.w3schools.com/jsref/jsref_unshift.asp#:~:text=%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:)我知道你要了 lodash,但我认为这也是一件需要注意的好事情:)

EDIT:编辑:

To clarify, this works the same whether you're pushing defined vars, string, arrays, objects or whatever:澄清一下,无论您是推送定义的变量、字符串、arrays、对象还是其他任何东西,这都是一样的:

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:将“pushArray”和“anotherArray”推到“yourArray”的开头,因此它的值如下所示:

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

Happy Coding!快乐编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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