I have array list of items like the below
let sourceList: SourceList[] = [
{
Value: "L7",
Name: "L7",
IsVisible: false
},
{
Value: "LO",
Name: "LO",
IsVisible: false
},
{
Value: "L3",
Name: "L3",
IsVisible: false
},
{
Value: "LS",
Name: "LS",
IsVisible: false
}
]
code tried so far
if(this.sourceList.indexOf("L7",0) != -1 && this.selectedSources.indexOf("LO",0) != -1 ){
}
but getting an error at "L7"
I am adding items from this souceList array to another array say array2 one by one ..
is there any way to check whether the item from the souceList array is in array2 or not ..
I need to do some process if item "L7" and "LO" is in array 2
but I am not able to figure out how can i search both the items at a time in array 2 ..
I am using angular 4 ..
Could any one please help on this, that would be very grateful to me
You can use the some method:
if (this.sourceList.some(x => x.Value === "L7") &&
this.selectedSources.some(x => x.Value === "L0")) {
...
}
Related
In my state I have an object called foodLog which holds all entries a user enters with one of the keys being foodSelectedKey and I'm trying to return all entries that have a matching value from that key with a different array called foodFilter.
However, this doesn't work and errors out saying foodLog.filter() isn't a function - I've looked this up and it's because it's an Object (I think). Any help would be greatly appreciated!
state = {
// log food is for the logged entries
foodLog: {},
// used for when filtering food entries
foodFilter: [],
};
findMatches = () => {
let foodLog = this.state.foodLog;
let foodFilter = this.state.foodFilter;
let matched = foodLog.filter((item) => {
return foodLog.foodsSelectedKey.map((food) => {
return foodFilter.includes(food);
});
});
};
I guess the reason behind the error Is not a function is that the object can not be looped. By that it means you can not iterate an object with differend variables inside, if it has no index to be iterated like an array. The same goes for map(), find() and similar functions which MUST be run with arrays - not objects.
As far as I understand you have an object named foodLog which has an array named foodsSelectedKey. We need to find intersected elements out of foodFilter with the array. This is what I came up with:
state = {
// log food is for the logged entries
foodLog: {
foodsSelectedKey: [
{ id: 1, name: "chicken" },
{ id: 2, name: "mashroom" }
]
},
// used for when filtering food entries
foodFilter: [
{ id: 1, name: "chicken" },
{ id: 2, name: "orange" }
]
};
findMatches = () => {
let foodLog = this.state.foodLog;
let foodFilter = this.state.foodFilter;
let matched = foodLog.foodsSelectedKey.filter((key) =>
{
for (let i=0; i<foodFilter.length;i++){
if(foodFilter[i].name===key.name)
return true
}
return false;
}
);
return matched;
};
The Output is filtered array, in this case, of one element only:
[{
id: 1
name: "chicken"
}]
In order to check the output - run console.log(findMatches()). Here is the CodeSandbox of the solution. (check console at right bottom)
I have the following code, which basically adds empty objects to an array.
handleAddNewRow = () => {
this.setState({
rowData: [
{ MEMBER: "", ALIAS: "", STATUS: "" },
...this.state.rowData
]
})
}
Lets say, I am passing an integer value to the function handleAddNewRow and then it dynamically adds the number of empty objects to the array based on the integer value, How is it possible?
You can look at my function:
handleAddNewRow = (number) => {
this.setState({
rowData: [
...this.state.rowData,
...(new Array(number).fill({ MEMBER: "", ALIAS: "", STATUS: "" }))
]
});
}
in the following code i wrote code in simple condition
change it on your own
const array = [{name: '', family: ''}]
function a(num, arr) {
let temp = [...arr, {name: '', family: ''}]
if (num - 1 > 0) {
temp = a(num - 1, temp)
}
return temp
}
const b = a(4, array)
console.log(b)
Ok, so we had some code that was working fine and passing tests fine on node 10, now following upgrading to node 11 the code now fails unit tests. Code maps over array of objects altering properties then sorts based on a string name value i.e. array.sort(a, b) => a.toLowerCase() > b.toLowerCase().
It now maps correctly but the sort does not work and returns the mapped array only without sorting, when i've tried splitting the two functions out into individual map then sort the sort returns undefined.
Have researched and tried to find some examples to see what needs to be changed but not found a great deal other than suggestions of the sort algorithm changing to timsort in v8.
simple code
export default places => places
.map(place => ({
value: place.properties.code, label: place.properties.name
}))
.sort((placeA, placeB) => placeA.label.toLowerCase() >
placeB.label.toLowerCase())
test array:
type: 'Place',
properties: {
code: 'CA076757',
name: 'Brockway'
}
}, {
type: 'Place',
properties: {
code: 'MN486464',
name: 'Ogdenville'
}
}, {
type: 'Place',
properties: {
code: 'S4889785',
name: 'North Haverbrook'
}
}]
expected result
{value: 'CA076757', label: 'Brockway'},
{value: 'S4889785', label: 'North Haverbrook'},
{value: 'MN486464', label: 'Ogdenville'}
]
actual result
{value: 'CA076757', label: 'Brockway'},
{value: 'MN486464', label: 'Ogdenville'}.
{value: 'S4889785', label: 'North Haverbrook'}
]
we had some code that was working fine and passing tests fine on node 10, now following upgrading to node 11 the code now fails unit tests
To be blunt, that means that your tests are not providing sufficient coverage ;-)
In JavaScript, a comparator function cmp(a, b) for Array.sort should return:
a value less than zero if a is less than b
zero if a is equal to b
a value greater than zero if a is greater than b
If you use a comparator function that returns a boolean value, then false will silently map to 0, and true will silently map to 1. There is no way to signal the a < b case. If your test cases get (or used to get) sorted correctly anyway, then they didn't cover that case.
A suitable comparator function for your example, regardless of which Node version or which browser you're using, would be:
(placeA, placeB) => {
let a = placeA.label.toLowerCase();
let b = placeB.label.toLowerCase();
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
You can use localeCompare for that:
export default places => places
.map(place => ({
value: place.properties.code, label: place.properties.name
}))
.sort((placeA, placeB) => placeA.label.toLowerCase().localeCompare(placeB.label.toLowerCase()));
Output:
[ { value: 'CA076757', label: 'Brockway' },
{ value: 'S4889785', label: 'North Haverbrook' },
{ value: 'MN486464', label: 'Ogdenville' } ]
Based on my answer to Sort array of objects by string property value, a sufficient way to sort strings when string locales are not important, is the following approach:
const sortBy = fn => (a, b) => {
const fa = fn(a)
const fb = fn(b)
return -(fa < fb) || +(fa > fb)
}
const sortByLabelCaseInsensitive = sortBy(
place => place.label.toLowerCase()
)
const fn = places => places.map(place => ({
value: place.properties.code,
label: place.properties.name
})).sort(sortByLabelCaseInsensitive)
const array = [{
type: 'Place',
properties: {
code: 'CA076757',
name: 'Brockway'
}
}, {
type: 'Place',
properties: {
code: 'MN486464',
name: 'Ogdenville'
}
}, {
type: 'Place',
properties: {
code: 'S4889785',
name: 'North Haverbrook'
}
}]
console.log(fn(array))
try this one
.sort((placeA, placeB) => {
if(placeA.label.toLowerCase() < placeB.label.toLowerCase()) return -1
if(placeA.label.toLowerCase() > placeB.label.toLowerCase()) return 1
return 0;
});
You need to compare each element with the next one and return that it is equal, greater or less
I have an object which is dynamically built. I need to get some of the fields of this object (exactly the dynamic ones) and parse them into an array.
In the code below, I need to transform the towers[X] into an array of objects.
{id: "", description: "Teste", towers[1]: true, towers[2]: true,
towers[3]: true, …}
description: "Test"
id: ""
towers[1]: true
towers[2]: true
towers[3]: true
towers[4]: ""
}
I want it to be something like:
{
id: ""
description: "Test",
towers[1]: true //Don't care if it stays here or not, will not use
...
}
And a new array like:
{
[id: 1, value: true],
[id: 2, value: true],
[id: 3, value: true],
[id: 4, value: ""]
}
Just going to guess towers[0] gives back a number, if it does you can do this. This will find all keys that have boolean values and keep them and append them to a object.
const obj = YOUROBJHERE;
Object.keys(obj ).filter((key) => tyepof obj[key] === "boolean").reduce((accum, key) => {
return {...accum, [key]: obj[key]};
}, {})
in case of X=number and obj is the object we want to transform
let result = [];
for (let indx = 1; indx <=x ; i++) {
result.push({value:indx,value: obj['towers'+indx]})
}
If you want to transform your array of object you can do some like:
this.obj=this.obj.map(obj=>{
return {
id:obj.id,
description:obj.description,
towers:Object.keys(obj).filter((key) => key.indexOf('towers') != -1 )
.map((k,index)=>{
return {id:index+1,value:obj[k]}
})
.filter((x:any)=>x.value)
}
})
See that, map allow an "index" (begins by 0)
I have an array in my state called columnToFilterOut. Let's say this is my array in my state: columnToFilterOut = ["first_col", "second_col", "third_col"]
I also have another array in state called rows that contains a list of dicts where there is a key called id that is corresponding to the values in columnToFilterOut. Here is an example of rows:
rows: [
{
id: "first_col",
numeric: false,
disablePadding: true,
label: "1"
},
{
id: "second_col",
numeric: true,
disablePadding: false,
label: "2"
},
{
id: "third_col",
numeric: true,
disablePadding: false,
label: "3"
},
{
id: "fourth_col",
numeric: true,
disablePadding: false,
label: "4"
}
]
As you can see, there is an extra element in there. The extra value is the one with id = "fourth_col". I want to delete all elements to make sure that both arrays match up.
Here is my delete function:
removeFromRowsById(id) {
console.log("IN REMOVE FUNCTION");
const filteredValues = this.state.rows.filter((_, i) => i["id"] !== id);
this.setState({ rows: filteredValues });
}
So I pass in an id and it should remove the value with the given id. Inside my render function, I use it like this:
Object.keys(rows).map(
(key, index) =>
!(columnToFilterOut.indexOf(rows[index]["id"]) > -1) //meaning the value doesn't exist inside of columnToFilterOut
? this.removeFromRowsById.bind(this, rows[index]["id"])
: console.log("Not deleting")
);
This isn't working. The value in the rows array is never removed. I print it to make sure. I also notice that my print statement inside of removeFromRowsById never logs to the console as though the function never actually gets called. Any help is great. Thanks!
try to change your this.state.rows.filter, to be like below. and see if it works
removeFromRowsById(id) {
console.log("IN REMOVE FUNCTION");
// 1. the original code should be === not !==, because you want to delete when the id matches.
// 2. the "i" should be on first parameter not second
const filteredValues = this.state.rows.filter((i, _) => i["id"] === id);
this.setState({ rows: filteredValues });
}
I changed the removeFromRowsById to look like this:
removeFromRowsById = index => {
console.log("IN REMOVE FUNCTION");
const newList = [...this.state.rows1];
newList.splice(index, 1);
this.setState(state => ({
rows1: newList
}));
};
And I call it regularly in the render function (without the binding). I think you needed to use the arrow function which fixed the issue and I revamped the way it deletes from the list in case what #vdj4y said was true