[英]How can I return all previous items in a JavaScript array than a current value?
Let's say I have an array:假设我有一个数组:
var myArr = new Array('alpha','beta','gamma','delta');
And that I want a function to return an array of all items before a given item:而且我想要一个函数来返回给定项目之前的所有项目的数组:
function getAllBefore(current) {
var myArr = new Array('alpha','beta','gamma','delta');
var newArr = ???
return newArr;
}
getAllBefore('beta'); // returns Array('alpha');
getAllBefore('delta'); // returns Array('alpha','beta','gamma');
What's the fastest way to get this?最快的方法是什么? Can I split an array on a value?我可以根据值拆分数组吗? Do I have to loop each one and build a new array on the fly?我是否必须循环每个并动态构建一个新数组? What do you recommend?您有什么推荐的吗?
What about if I wanted the opposite, ie getAllAfter()
?如果我想要相反的东西,即getAllAfter()
怎么办?
function getAllBefore(current) {
var myArr = new Array('alpha','beta','gamma','delta');
var i = myArr.indexOf(current);
return i > -1 ? myArr.slice(0, i) : [];
}
Get the index of the specified item. 获取指定项的索引。 If found, .slice()
from 0 to that index. 如果找到, .slice()
从0到该索引。 If not found, return an empty array (or whatever other default value you like). 如果未找到,则返回一个空数组(或您喜欢的任何其他默认值)。
Note that .indexOf()
is not supported (for arrays) in IE8 and older, but there is a shim you can use, or you could just use a simple for
loop instead. 请注意,IE8及更早版本中不支持(对于数组) .indexOf()
,但是您可以使用垫片 ,或者您可以使用简单的for
循环。
javascript slice array javascript 切片数组
// array.slice(start, end)
const FRUITS = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = FRUITS.slice(1, 3);
// citrus => [ 'Orange', 'Lemon' ]
// Negative values slice in the opposite direction
var fromTheEnd = FRUITS.slice(-3, -1);
// fromTheEnd => [ 'Lemon', 'Apple' ]
array cut only last 5 element数组只切割最后 5 个元素
arr.slice(Math.max(arr.length - 5, 0))
使用indexOf
和slice
:
newArr = myArr.slice(0, myArr.indexOf(current));
Try something like this 尝试这样的事情
var index = myArr.indexOf('beta');
var before = myArray.slice(0, index);
I recently had to do something like this for an array of objects.我最近不得不为一组对象做这样的事情。 This is what I went with:这就是我的经历:
const myArr = [
{ controlId: 1, value: 'alpha'},
{ controlId: 2, value: 'beta' },
{ controlId: 3, value: 'gamma' },
{ controlId: 4, value: 'delta'}
];
function getAllBefore(id) {
const index = myArr.findIndex( ({ controlId }) => controlId === id);
return myArr.filter((_, i) => i < index);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.