Javascript 从过滤器方法javascript返回索引值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26468557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return index value from filter method javascript
提问by alsco77
So I have an array of objects in my angular controller, and I want to return the value of the index of the field within the array which has a matching ID to my parameter. There will only be one object in the array with a matching fieldId..
所以我的角度控制器中有一个对象数组,我想返回数组中字段索引的值,该字段的 ID 与我的参数匹配。数组中将只有一个对象具有匹配的 fieldId..
$scope.indexOfField = function(fieldId) {
return $scope.model.fieldData.filter(function(x) {
if (x.Id === fieldId) {
return // ???????
}
});
}
采纳答案by Ruben Nagoga
You can't return index from filter method.
您不能从 filter 方法返回索引。
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
filter() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
You can use forEach
您可以使用 forEach
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
filter() 方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
$scope.indexOfField = function(fieldId) {
var i;
return $scope.model.fieldData.forEach(function(x, index) {
if (x.Id === fieldId) {
i = index;
}
});
// use i
}
or even better to use foras you can't stop forEach when you have found your id.
甚至更好地使用,for因为当您找到您的 ID 时,您无法停止 forEach。
$scope.indexOfField = function(fieldId) {
var fieldData = $scope.model.fieldData,
i = 0, ii = $scope.model.fieldData.length;
for(i; i < ii; i++) if(fieldData[i].Id === fieldId) break;
// use i
}
回答by Jivings
From the Array.prototype.filterdocumentation:
callback is invoked with three arguments:
- the value of the element
- the index of the element
- the Array object being traversed
使用三个参数调用回调:
- 元素的值
- 元素的索引
- 正在遍历的 Array 对象
However you should probably be using the somefunction if there is only one instance in your array (as it will stop as soon as it finds the first occurrence), and then find the index using indexOf:
但是,some如果数组中只有一个实例,则您可能应该使用该函数(因为它会在找到第一个实例后立即停止),然后使用indexOf以下命令查找索引:
var field = $scope.model.fieldData.filter(function(x) {
return x.Id === fieldId;
})[0];
var index = $scope.model.fieldData.indexOf(field);
Or iterate the array until you find the correct element:
或者迭代数组,直到找到正确的元素:
var index;
$scope.model.fieldData.some(function(x, i) {
if (x.Id === fieldId) return (index = i);
});
回答by Dean Jones
ARRAY (FIND MULTIPLE INDEXES) METHOD
数组(查找多个索引)方法
[10, 7, 13, 15, 230].map((e,i) => e > 13 ? i : undefined).filter(x => x)
//returns [3, 4](*** RETURNS multiple indexes ***)
//FILTER (is simply just REMOVING the UNDEFINED elements (which are FALSY and considered the same as FALSE)
otherwise you'll get...
否则你会得到...
[10, 7, 13, 15, 230].map((e,i) => e > 13 ? i : undefined) //returns?[undefined, undefined, undefined, 3, 4]
RETURN MULTIPLE INDEXES (replaces findIndex METHOD)
返回多个索引(替换 findIndex 方法)
[1, 1, 2, 2, 2, 3, 4, 5].map((e,i) => e === 2 ? i : undefined).filter(x => x) //returns [2, 3, 4]
RETURN MULTIPLE VALUES (replaces find METHOD)
返回多个值(替换查找方法)
[5, 12, 8, 130, 44].map((e,i) => e > 13 ? e : undefined).filter(x => x) // returns [130, 44]
回答by quime parle
The findIndex method returns the index of the first element of the array that satisfies a condition given by a function. If the function returns false for all elements of the array, the result is -1.
findIndex 方法返回数组中满足函数给定条件的第一个元素的索引。如果函数对数组的所有元素都返回 false,则结果为 -1。
See the documentation here
In my example, x is an item for each iteration and i use cross function for my condition.
请参阅此处的文档
在我的示例中,x 是每次迭代的一个项目,我对我的条件使用交叉函数。
I hope I help you
我希望我能帮助你
const datas = [];
const fieldId = 5;
let index = datas.findIndex(x => x.Id === fieldId);
回答by T.J. Crowder
The second argument to your callback is the index. I can't quite make out what you want your function to do/return, but if you add , indexafter function(x, that will give you access to the index for that iteration.
回调的第二个参数是索引。我不能完全弄清楚你想让你的函数做什么/返回什么,但是如果你添加, indexafter function(x,这将使你可以访问该迭代的索引。
Working from the nameof your function, I don't think you want filterat all:
从您的函数名称开始,我认为您根本不需要filter:
$scope.indexOfField = function(fieldId) {
var result = -1;
$scope.model.fieldData.some(function(x, index) {
if (x.Id === fieldId) {
result = index;
return true;
}
});
return result;
}
Array#somestops as of the first iteration that returns a truthy value, so we'll stop searching the first time we find a match.
Array#some从返回真值的第一次迭代开始停止,因此我们将在第一次找到匹配项时停止搜索。
回答by JustAnotherDeveloper
You cannot return directly the index but you can set the 'thisArg' parameterand set data inside it. This is cleaner than a global variable.
您不能直接返回索引,但可以设置'thisArg' 参数并在其中设置数据。这比全局变量更干净。
var data = {
indexes: []
};
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.filter(function (element, index) {
if (element%2 == 0) {
this.indexes.push(index);
return true;
}
}, data);
console.log(data.indexes); // [1, 3, 5, 7, 9]
data.indexes.forEach(function(value) {
console.log(myArray[value]);
}); // 2, 4, 6, 8, 10
回答by Ferran Maylinch
Some languages can mapa collection into an indexed collection where each element is mapped to a pair of {element, index}. That way you can map/filter/etc using any of those two values.
某些语言可以map将集合转换为索引集合,其中每个元素都映射到一对{element, index}. 这样你就可以使用这两个值中的任何一个来映射/过滤/等。
For example, Kotlin has withIndexand Swift has enumerated.
例如,Kotlin 有withIndex并且 Swift 有enumerated。
Javascript doesn't have that method, AFAIK. But you can easily build yours or use a workaround.
Javascript 没有这种方法,AFAIK。但是您可以轻松构建自己的或使用解决方法。
Workaround (not recommended)
解决方法(不推荐)
// Turn an array of elements into an array of {value, index}
const indexedArray = array.map((v,i) => ({value:v, index:i}));
// Now I can filter by the elem but keep the index in the result
const found = array.filter(x => x.value === someValue)[0];
if (found) {
console.log(`${found.value} found at index ${found.index}`);
}
// One-liner for the question scenario, using some new js features.
// Note that this will fail at the last ".i" if the object is not found.
const index = fieldData.map((v,i) => ({v,i})).filter(x => x.v.id == fieldId)[0].i
Add a withIndexmethod to Array(recommended):
添加一个withIndex方法到Array(推荐):
This is basically the same as the workaround, but creating a reusable function, which makes it much cleaner.
这与解决方法基本相同,但创建了一个可重用的函数,这使得它更简洁。
Array.prototype.withIndex = function() {
return this.map((v,i) => ({value: v, index: i}))
};
// Now the one-liner would be:
const index = fieldData.withIndex().filter(x => x.value.id == fieldId)[0].index;
// Better, with null checking:
const found = fieldData.withIndex().filter(x => x.value.id == fieldId)[0];
if (found) {
console.log(`${found.value} found at index ${found.index}`);
}
回答by A.R Naseef
Use the findIndex.
You can use this function. When the condition is met first, the index is returned.
使用findIndex. 您可以使用此功能。当首先满足条件时,返回索引。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
回答by Matt
Filter will not return the index, but you can do something like this.
Filter 不会返回索引,但你可以做这样的事情。
$scope.indexOfField = function(fieldId) {
$scope.model.fieldData.filter(function(x, i) {
if (x.Id === fieldId) {
var indexOfField = i;
}
});
return indexOfField;
};
回答by Foysal Ahmed Emon
function modifyArray(nums) {
let newNums = nums.filter((num,index) => {
return num = num % 2 ? num * 3 : num * 2;
})
return newNums;
}
Here the index is the increment value you are looking for.
这里的索引是您要查找的增量值。

