This question have two parts: first, I want to create an array that works like a table. It will have two columns ids (Game-Id and Game-Name). I have been working in something like this:
var game_list =
[
{id:1, name:'Vampires hunter'},
{id:2, name:'Christmas vampires'},
{id:3, name:'Fruit hunter'},
{id:4, name:'The fruitis'},
{id:5, name:'james bond'},
{id:6, name:'Vampires hunter'},
{id:7, name:'Vampires avalon'},
{id:8, name:'Vampires warrior'},
{id:9, name:'Vampires hunter'},
{id:10, name:'Vampires hunter'},
];
But I'm not able to access elements in this kind of array / object, not even a document.write of an element.
What I need is to create a function that will search for a specific string inside that array. The function will have 2 parameters (the string and the array) and it will give us a result an array of the elements with game names and ids that match that string.
Use filter:
function filter(arr, string) {
return arr.filter(function (el) {
return el.name === string;
});
}
filter(game_list, 'Vampires avalon'); // [{ id=7, name="Vampires avalon"}]
Demo
If you want to be really clever, add some regex to match the string anywhere in the name:
function filter(arr, string) {
var regex = new RegExp('.*' + string + '.*');
return arr.filter(function (el) {
return regex.exec(el.name);
});
}
filter(game_list, 'hunter');
Which will give you this:
[{"id":1,"name":"Vampires hunter"},{"id":3,"name":"Fruit hunter"},{"id":6,"name":"Vampires hunter"},{"id":9,"name":"Vampires hunter"},{"id":10,"name":"Vampires hunter"}]
Demo
A simple loop and check will do:
function checkArray(name) {
var arr = [];
for (var i = 0; i < game_list.length; i++) {
if (game_list[i].name == name)
arr.push(game_list[i])
}
return arr;
}
Will compare the name passed in with the name of each object, and returns an array of matching objects. If you only want names containing the passed in string, use indexOf and check on -1
Related
I'm still VERY new to Javascript and I'm having trouble with looping through an array and replacing items. I hope this explanation is clear.
I have an array that looks like this:
[
'1:1', 'blah',
'1:2', undefined,
'1:3', 'smith',
'1:4', 'blah',
'1:5', 'williams',
'1:6', 'blah',
'1:7', 'blah'
]
and I have another array that looks like this:
[
'taylor',
'smith',
'williams',
'brown'
]
I want to replace any value in the first Array that isn't in a /([0-9]+):([0-9]+)/g format and isn't found in the second array. So all the "blah" and "undefined" in the first Array should be replaced with johnson but the names that match the second Array and the #:# numbers still remain, so the output shows:
[
'1:1', 'johnson',
'1:2', 'johnson',
'1:3', 'smith',
'1:4', 'johnson',
'1:5', 'williams',
'1:6', 'johnson',
'1:7', 'johnson',
]
We can use a simple if statement inside a for loop to achieve what you are looking for.
var originalArray = [
'1:1', 'blah',
'1:2', undefined,
'1:3', 'smith',
'1:4', 'blah',
'1:5', 'williams',
'1:6', 'blah',
'1:7', 'blah'
];
var matchArray = [
'taylor',
'smith',
'williams',
'brown'
];
for (var i = 0; i < originalArray.length; i++) {
var value = originalArray[i];
//Check if it matches your RegEx
if (value !== undefined) {
var doesItMatchRegEx = value.match(/([0-9]+):([0-9]+)/g);
} else {
originalArray[i] = "johnson";
}
//Check if it is in your second array
var isItInSecondArray = matchArray.includes(value);
if (!doesItMatchRegEx && !isItInSecondArray) {
//Let's replace it with Johnson
originalArray[i] = "johnson";
}
}
console.log(originalArray);
Let's call the main array arr and the array of names names, then this should do the trick:
arr.map(item => !/([0-9]+):([0-9]+)/g.test(item) && !names.includes(item) ? 'johnson' : item)
I would recommend a functional approach using the map() function of the array. Alternatively could use a filter(), but since you want to replace certain entries the map does it with less steps.
The Array.prototype.map() method takes in a function that will be called on each item in the array, and the return of that function will go in that index of the return.
validNames = [‘taylor’...];
numberFormatRegex = /([0-9]+):([0-9]+)/g;
// This function will run on each value in the array, and the RETURN becomes the new value in the array created after mapping
mapFunction = (value) => {
if(!validNames.includes(value) && !numberFormatRegex.test(value)){
// only values NOT in the validNames list AND (&&) NOT passing the refer will enter this branch
return ‘Johnson’;
}
// This only runs if the previous return didn’t so it will only happen for valid values
}
// Call map() method with our new function and save result to new array
// note that the inputArray will be unchanged and a new one will be returned and assigned to newArray
newArray = inputArray.map(mapFunction);
How to remove an array from json array in react js. I tried something like this. but not working
Now the response is directly set to atate as follows
let { newData} = response;
please help to filter item. Either from response or from state variable
response.map((res, index) => {
if (res.status==1) {
res.splice(index, 1) // remove element
};
})
response is [object Object] when i alerted
[
{id:1, status:1},
{id:2, status:0},
{id:3, status:1},
]
Use filter instead of map and filter out the unwanted object/s.
const filteredArray = response.filter((res) => res.status !== 1);
Please just be aware that this will create a new array and not mutate your original array.
You should create a new one of Array, You can try..
let temp = []
response.forEach((res, index) => {
if (res.status !== 1) {
temp.push(res)
}
})
The better solution is to use the filter method, or if you still want to use the splice, It should be response.splice
Note: Using the splice approach is wrong as pointed out by #VLAZ, as it shifts the elements but the indexing by forEach will continue irrespective of the elements spliced off.
var response = [
{id:1, status:1},
{id:2, status:0},
{id:3, status:1},
]
response.forEach((res, index) => {
if (res.status==1) {
response.splice(index, 1) // remove element
};
})
console.log(response);
I have the following angular array for one of my select tags
var names= [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}];
$scope.names =names;
$scope.FormData = {};
$scope.FormData.name = $scope.names[1];
In the above array, instead of selecting the item by index (1), how can I select the item by name or the val, like
$scope.FormData.name = $scope.names['2']; #will select the {name: 'Batman', val: '2'}
I initially posted a lengthy question here, but then I realized this is the more simpler / focus way of my question
If you are using angular, why not use the build in $filter?
https://docs.angularjs.org/api/ng/filter/filter
In your case, if you want to filter in the controller, the code bellow will retrieve an Array with all the occurrences inside names that match the search for 'Superman':
$filter('filter')($scope.names, {name:'Superman'})
If you are confident that there will be at least one match you could do this in order to get the first match:
var matches = $filter('filter')($scope.names, {name:'Superman'});
var match = matches[0]:
Bare in mind that if there are no matches then match will be undefined
If you want a re-useable function you could do it like this:
$scope.find = function(list, attributeName, attributeValue){
var returnVal = {};
angular.forEach(list,function(item){
if(item[attributeName]){
if(item[attributeName] === attributeValue){
returnVal = item;
}
}
});
return returnVal;
};
$scope.FormData.name = $scope.find(names,'name','Batman');
In the above array, instead of selecting the item by index (1), how
can I select the item by name
You can use the find method of the Lodash library (http://lodash.com/docs#find):
var names= [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}];
var matchingBatman = _.find(names, { name: 'Batman' });
matchingBatman is: {name: 'Batman', val: '2'}
You can do the same if you want to find by val:
var matchingBatman = _.find(names, { val: '2' });
If you want to write a function instead of using a library
function selectByProperty(key, val){
for(var i=0; i< $scope.names.length; i++){
if($scope.names[i][key] === val){
return $scope.names[i];
}
}
}
$scope.FormData.name = selectByProperty('val','2');
This question already has answers here:
Remove array element based on object property
(12 answers)
Closed 8 years ago.
I have array like this
var curChanges = [
{id:1, isChecked:true},
{id:2, isChecked:false},
{id:3, isChecked:true}
];
Now, if i want to remove second array i.e {id:2, isChecked:false} dynamically, How do i do?
Here id is unique.
Thanks in advance.
Firstly, you have a syntax error. Object property values are set with :, not with =:
var curChanges = [
{
id: 1,
isChecked: true
},
// etc...
];
Assuming the order of elements in the array is not fixed, the easiest way to achieve what you're trying to do will be to use the ES5 Array.prototype.filter method:
curChanges.filter(function (elem) {
return elem.id !== 2;
});
If you return true from the filter function, the element will stay in the array. If you return false, it will be removed.
first off, invalid array. Should be : not =
so it becomes:
var curChanges = [ {id:1, isChecked:true}, {id:2, isChecked:false}, {id:3, isChecked:true}];
Use a filter to remove based on id:
curChanges.filter(function(i) { return i.id!=2;})
Or to directly remove the second element :
curChanges.splice(1,1);
When I type G in the field and it filters out all the names whose names contain g in any part of their name. I want only to filter which starts with G. To sort this, i added something like this.
patientSearchResult[i].LastName.toUpperCase().charAt(0)
But now when i type Gr. i don't get Greg's result... why?
You could use a regular expression coupled with an array filter for this. Try this:
var patients = [
"Greg",
"Anna",
"Slartibartfarst"
];
var input = "Gr";
var re = new RegExp(input+'.+$', 'i');
patients = patients.filter(function(e, i, a){
return e.search(re) != -1;
});
console.log(patients);
http://jsfiddle.net/2R44X/
charAt returns just the character at the specified index.
You could use patientSearchResult[i].LastName.toUpperCase().substr(0,2) where 2 should be replaqced with the length of the string you're searching for.
For a more generic solution, you could use Array.filter with regexp searches to make query functions:
var patientRecord = [
{firstname: 'Bob',lastname: 'Grown'},
{firstname: 'Alexa',lastname: 'Ace'},
{firstname: 'Chris',lastname: 'Green'}
];
var makeQuery = function(property, regexp) {
// return a callback function for filter, see MDC docs for Array.filter
return function(elem, index, array) {
return elem[property].search(regexp) !== -1;
};
};
var q = makeQuery('lastname', /^g/i); // ^ = from beginning, i = "ignore case"
patientRecord.filter(q);
Console output:
[
{
firstname: "Bob",
lastname: "Grown",
__proto__: Object
},
{
firstname: "Chris",
lastname: "Green",
__proto__: Object
}
]