Filter array based on an array of index
The simplest way is to use _.map
on arr2
, like this
console.log(_.map(arr2, function (item) {
return arr1[item];
}));
// [ 77, 33, 8 ]
Here, we iterate the indexes and fetching the corresponding values from arr1
and creating a new array.
Equivalent to the above, but perhaps a bit more advanced, is to use _.propertyOf
instead of the anonymous function:
console.log(_.map(arr2, _.propertyOf(arr1)));
// [ 77, 33, 8 ]
If your environment supports ECMA Script 6's Arrow functions, then you can also do
console.log(_.map(arr2, (item) => arr1[item]));
// [ 77, 33, 8 ]
Moreover, you can use the native Array.protoype.map
itself, if your target environment supports them, like this
console.log(arr2.map((item) => arr1[item]));
// [ 77, 33, 8 ]
Filter array of objects by index
I think this will works
deleteNote(i) {
this.lists = this.lists.filter((_, index) => index !== i);
}
Return index value from filter method javascript
You can't return index from filter method.
The filter() method creates a new array with all elements that pass
the test implemented by the provided function.
You can use forEach
$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 for
as you can't stop forEach when you have found your id.
$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
}
Best way to filter an array of objects by Index in JavaScript
The best way to filter the array by index is using the slice()
method:
const productArrayFiltered = productArray.slice(0, 2);
From MDN:
The
slice()
method returns ashallow copy
of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array.The original array will not be modified.
Side note: it's important to remember that the method returns a new array that must be assigned to a new constant or variable.
Filter array by indices
IndexSet
is a collection of increasing integers, therefore you can
map each index to the corresponding array element:
let array = ["sun", "moon", "star", "meteor"]
let indexSet: IndexSet = [2, 3]
let result = indexSet.map { array[$0] } // Magic happening here!
print(result) // ["star", "meteor"]
This assumes that all indices are valid for the given array.
If that is not guaranteed then you can filter the indices
(as @dfri correctly remarked):
let result = indexSet.filteredIndexSet { $0 < array.count }.map { array[$0] }
Filtering a nested array based on 2 or more values in specific indices
Since you want to filter an Array where indexes and values matches, pass an Object as the second argument, where the property is the unique index and the value is the string to match.
Since array indexes are unique-per-se an object is the best fit since its properties must also be unique.
Than use a combination of: Array.prototype.filter, Array.prototype.every and finally match by Object.entries pairs:
/**
* Filter Array of sub-Arrays where "indexes have value"
* @param {Array} arr Array to filter
* @param {Object} ob Object with index/value pairs
* @return {Array} A filtered array of subarrays.
*/
const filterByIndexValue = (arr, ob) =>
arr.filter(sub => Object.entries(ob).every(([i, v]) => sub[i] === v));
// DEMO TIME:
const test_array = [
["0", "0.1", "4.2", "Kramer Street"],
["3", "4.2", "7.1", "Kramer Street"], // << get this one
["6", "0.2", "3.5", "Lamar Avenue"],
["99", "4.2", "99.1", "Kramer Street"], // << get this one
];
// Filter test_array where sub-arrays
// index 1 has value "4.2" and
// index 3 has value "Kramer Street"
const new_array = filterByIndexValue(test_array, {
1: "4.2",
3: "Kramer Street"
});
console.log(new_array);
Use index array to filter another array
You can utilize the native javascript .filter()
method to solve this kind of problem.
var arr = ["aaa", "xxx", "aaa", "xxx", "aaa"];
var foundIn = [1, 3];
var res = arr.filter(function (eachElem, index) {
return foundIn.indexOf(index) == -1
})
console.log(res) // ["aaa", "aaa", "aaa"]
Explanation
The callback will be executed in each loop on where this function is called (in the example above example, it will be used on arr
variable).
Two arguments are passed into the callback. First is the element, and the second is the index. Because you need the index
, you have to write all those two arguments, even though you are not using the first argument.
In this issue, the index
variable is used to determine whether it exists on the foundIn
variable or not (we use .indexOf()
method to do the checking). If it's not exists, true
will be given. So all returned element is the one which is not exists in the foundIn
.
.indexOf()
returns the index of the searched item, if it's not found, -1
is returned.
If you are using es6, you can simplify the code:
var res = arr.filter((d, i) => foundIn.indexOf(i) == -1)
Also try this working example:
var arr = ["aaa", "xxx", "aaa", "xxx", "aaa"];
var foundIn = [1, 3];
var res = arr.filter(function (eachElem, index) {
return foundIn.indexOf(index) == -1
})
document.write(JSON.stringify(res))
// ["aaa", "aaa", "aaa"]
Javascript: Filter Array by List of Array Index Numbers
You need to use the filter method of an array to filter based on the index as provided in the filterList.
var arr = [
{
documentNumber: '2',
situsAddress:"123 Oak"
},
{
documentNumber: '7',
situsAddress:"567 3rd Avenue"
},
{
documentNumber: '9',
situsAddress:"895 Washington St"
},
{
documentNumber: '3',
situsAddress:"894 Forest Road"
}
]
var filterList = [0,2];
var result = arr.filter((obj,index) => filterList.includes(index));
console.log(result)
OR
filterList.map((item) => arr[item]))
Related Topics
A Lighter Way of Discovering Text Writing Direction
Will iOS Awake My App When I Receive Silent Push Notification(When App Is Not in Running State)
Preventing Avcapturevideopreviewlayer from Rotating, But Allow UI Layer to Rotate with Orientation
How to Load Multiple Storyboard Files Depending on iOS Version? (5 and 6)
Swift- Custom Uitableviewcell Delegate to Uiviewcontroller Only One Protocol Works
Getting System Uptime in iOS/Swift
Open Viewcontroller from Tab Like in Instagram Camera Page on iOS
How to Record a Video with Augmented Reality
Creating a Custom Progress Bar with Images
Uialertview Is Not Working in Swift
Sort Array by Distance Near User Location from Firebase
Getting the Local iPhone Number Through Sdk
How to Default Uilabel Font and Size Using Swift
Objective C- Trouble Updating UI on Main Thread
iOS Facebook Login "Given Url Is Not Allowed by the Application Configuration"