Searching for data in arrays [Node.JS] - arrays

I have a question:
(sorry for the bad formatting)
I have an array:
[
{
"data": [
[
"kek",
"lol"
],
[
"notkek",
"notlol"
]
]
}
]
If someone writes "kek" it should search it in the "data" array and return the "kek" position inside its array
(["kek","lol"])
and its array position
{
"data": [
[
"kek",
"lol"
]}
(in this case "data[0]")
If anybody knows the answer, please help me

The method Array.findIndex and Array.includes may help you
const obj = {
data: [
[
'kek',
'lol'
],
[
'notkek',
'notlol'
],
],
};
const keyToSearch = 'kek';
// We look for the key
const index = obj.data.findIndex(x => x.includes(keyToSearch));
if (index === -1) {
console.log(`We didn't found ${keyToSearch}`);
} else {
console.log(`We found ${keyToSearch} at index ${index}`);
}
Double index recuperation
const obj = {
data: [
[
'kek',
'lol'
],
[
'notkek',
'notlol'
],
[
'notkek',
'notlol',
'otherstuff',
'kek',
'test',
],
],
};
const keyToSearch = 'kek';
const ret = obj.data.reduce((tmp, x, xi) => {
// We look for the key
const index = x.findIndex(y => y === keyToSearch);
if (index === -1) return tmp;
return [
...tmp,
{
absoluteIndex: xi,
relativeIndex: index,
},
];
}, []);
if (!ret.length) {
console.log(`We didn't found ${keyToSearch}`);
} else {
ret.forEach(({
absoluteIndex,
relativeIndex,
}) => console.log(
`We found ${keyToSearch} at`,
`data index ${absoluteIndex}, in ${relativeIndex} position`,
));
}

userInput = 'kek'
let item = data.map((item, indx) => {
item.includes(userInput) ? return({"indx":indx,"nestedIndex":item.indexOf(userInput)}) : null
})
map over the data array and if the nested array had the item your searching for than return the index of the array and the index of the item with in that array

Related

How to merging two lists in React?

I need help with merging 2 lists in ReactJs.
for example,
list one :
[
{id:1,name:"abc",city:"ddd"},
{id:2,name:"cde",city:"ddd"},
{id:3,name:"ttt",city:"fff"}
]
list two:
[
{id:1,name:"abc"},
{id:3,name:"ttt"}
]
and the result that I want to get is
[
{id:1,name:"abc",city:"ddd"},
{id:3,name:"ttt",city:"fff"}
]
What is the best clearly way to do that?
You can use filter and some array method.
const arr1 = [
{id:1,name:"abc",city:"ddd"},
{id:2,name:"cde",city:"ddd"},
{id:3,name:"ttt",city:"fff"}
];
const arr2 = [
{id:1,name:"abc"},
{id:3,name:"ttt"}
];
const filteredArray = arr1.filter((el) => {
return arr2.some((x) => {
return x.id === el.id && x.name === el.name;
});
});
console.log(filteredArray);

Replace a string in array of objects in typescript

I have got a list of array objects as shown below
[
{
"subjectID": 1
"Chosen" : "{subjectsChosen:Python,java,Angular}"
"password": "{studentpw:123456abcd}"
},
{
"subjectID": 2
"Chosen" : "{subjectsChosen:SQL,Rprogram,React}"
"password": "{studentpw:987654zyxwv}"
}
]
Here I would like to remove the special characters and its notations and expected to populate array as shown below using typescript
[
{
"subjectID": 1
"Chosen" : "Python,java,Angular"
"password": "23456abcd"
},
{
"subjectID": 2
"Chosen" : "SQL,Rprogram,React"
"password": "987654zyxwv"
}
]
Thank you in advance
try this
for (let i = 0; i < subs.length; i++) {
subs[i].Chosen = removeSymbols(subs[i].Chosen);
subs[i].password = removeSymbols(subs[i].password);
}
function removeSymbols(s: string) {
return s.replace(/[\{\}]/g, "").split(":")[1];
}
result
[
{
"subjectID": 1,
"Chosen": "Python,java,Angular",
"password": "123456abcd"
},
{
"subjectID": 2,
"Chosen": "SQL,Rprogram,React",
"password": "987654zyxwv"
}
]
Welcome, is your object properties special characters limited to '{', ':', '}', if so, I propose to you the bellow solution, that I have tried and give a result as the one you have expected:
let objs = [
{
subjectID: 1,
Chosen: "{subjectsChosen:Python,java,Angular}",
password: "{studentpw:123456abcd}"
},
{
subjectID: 2,
Chosen: "{subjectsChosen:SQL,Rprogram,React}",
password: "{studentpw:987654zyxwv}",
}
];
objs.forEach((cur) => {
Object.keys(cur).forEach(key => {
if (typeof cur[key] === 'string') {
cur[key]=cur[key].replace(/[\{\}]/g, '').split(':')[1];
}
})
});
console.log(objs);
You could use any array operator function other than forEach.
We could use map operator of Array here to transform each item. To transform Chosen and password fields, we could use Regex and replace method of string.
const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const myText = "{subjectsChosen:Python,java,Angular}";
myText.replace(re, '$1'); // Python,java,Angular
Below is the full implementation that transform each item.
const items = [
{
"subjectID": 1,
"Chosen" : "{subjectsChosen:Python,java,Angular}",
"password": "{studentpw:123456abcd}"
},
{
"subjectID": 2,
"Chosen" : "{subjectsChosen:SQL,Rprogram,React}",
"password": "{studentpw:987654zyxwv}"
}
];
const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const passwordRegex = new RegExp(/\{studentpw:(.+)\}/, 'i')
const transformedItems = items.map(item => {
return {
...item,
"Chosen": item.Chosen.replace(chosenRegex, '$1'),
"password": item.password.replace(passwordRegex, '$1')
}
});
console.log(transformedItems);
We could also literally use a single regex if we don't want to differentiate them.
const transformRegex = new RegExp(/\{(.+):(.+)\}/, 'i');
....
return {
...item,
"Chosen": item.Chosen.replace(transformRegex, '$2'), // Since there are two regex groups now, use $2
"password": item.password.replace(transformRegex, '$2')
}

How to retain the array value even after Filter using es6

I am filtering the multidimensional array. After the successful filter the original array value is getting changed. Please find the array and filter method i am using
const rDetailsList = [
{
"rDate":"April 01, 2018",
"rList":[
{
"aName":"GOKQG C HQFUDHFPX",
"aNumber":"P3799838628"
},
{
"aName":"IGNDPJR D EKYJYC",
"aNumber":"P3899820579"
}
]
},
{
"rDate":"Jan 01, 2018",
"rList":[
{
"aName":"",
"aNumber":"A39A4035073"
},
{
"aName":"YVTLW K SIGLC",
"aNumber":"A270M040558"
}
]
}
];
const myFilter = (arr, num) => {
const rDetails = arr.filter(det => !!det.rList.find(l => l.aNumber === num));
return rDetails.map(det => {
det.rList = det.rList.filter(l => l.aNumber === num);
return det;
});
};
When i do console.log(myFilter(rDetailsList, 'A270M040558')) i am getting the result as expected as below
[{
"rDate":"Jan 01, 2018",
"rList":[
{
"aName":"YVTLW K SIGLC",
"aNumber":"A270M040558"
}
]
}]
But when i do console.log(rDetailsList) i am getting below result
const rDetailsList = [
{
"rDate":"April 01, 2018",
"rList":[
{
"aName":"GOKQG C HQFUDHFPX",
"aNumber":"P3799838628"
},
{
"aName":"IGNDPJR D EKYJYC",
"aNumber":"P3899820579"
}
]
},
{
"rDate":"Jan 01, 2018",
"rList":[
{
"aName":"YVTLW K SIGLC",
"aNumber":"A270M040558"
}
]
}
];
Anyone Please help why the one of the object is removed in "rDate":"Jan 01, 2018". Need solution to fix this as well.
Instead of
return rDetails.map(det => {
det.rList = det.rList.filter(l => l.aNumber === num);
return det;
});
do
return rDetails.map(det => {
return {
...det,
rList: det.rList.filter(l => l.aNumber === num)
}
});

array with objects containing array

Sorry guys if my way of asking the question in the title is not correct.
I am working on a project on react js and I am getting the data like this
[
{
"count": [
{
"1": 16
},
{
"1": 149
}
],
"day": "2019-08-27"
}
]
now this is my first time I am dealing with this kind of data and I really have no idea how can I show it like this I am really sorry guys I literally can't even show what I have tried because it does not seem relevant
[
{
count: 165
day:"2019-08-27"
}
}
Assuming the data you're getting is under a variable called data you could use reduce:
The below makes the assumption the count is always an array of objects with just 1 key called '1'.
const newData = data.map(datum => {
datum.count = datum.count.reduce((count, item) => {
return count + item['1']
}, 0)
return datum
})
You can try something like this:
let arr = [
// item
{
count: [
{
"1": 16
},
{
"1": 149
}
],
day: "2019-08-27"
}
];
arr.map(item => {
Object.keys(item).map(key => {
console.log(item[key])
// if item[key] is iterable
if(Array.isArray(item[key])) {
item[key].map(val => {
console.log(item)
})
} else {
console.log(item[key])
}
});
});
The concept is that for Objects you do a Object.keys().something and for an array you do a arr.map(item => ...)

merging nested lists and map in ruby

I have following list of maps, how can I get values inside map out and merge them as a new list
Example:
x = [ { "key1" => [{"K1" =>"123", "K2" =>"123"}] },
{ "key1" => [{"K3" =>"23", "K4" =>"32"}] },
{ "key1" => [{"K5" =>"34", "K6" =>"23"}] }]
What I want is:
[{"K1" =>"123", "K2" =>"123"},
{"K3" =>"23", "K4" =>"32"},
{"K5" =>"34", "K6" =>"23"}]
You can try the below -
x = [ { "key1" => [{"K1" =>"123", "K2" =>"123"}] },
{ "key1" => [{"K3" =>"23", "K4" =>"32"}] },
{ "key1" => [{"K5" =>"34", "K6" =>"23"}] }]
y = x.map{|h| h.map{|i,j| j} }.flatten
print(y)
This prints the below
[{"K1"=>"123", "K2"=>"123"}, {"K3"=>"23", "K4"=>"32"}, {"K5"=>"34", "K6"=>"23"}]
x.flat_map(&:entries).group_by(&:first).map{|k,v| Hash[k, v.map(&:last)]}
as:
> x = [ { "key1" => [{"K1" =>"123", "K2" =>"123"}] },
{ "key1" => [{"K3" =>"23", "K4" =>"32"}] },
{ "key1" => [{"K5" =>"34", "K6" =>"23"}] }]
> x.flat_map(&:entries).group_by(&:first).map{|k,v| Hash[k, v.map(&:last)]}
=> [{"key1"=>[[{"K1"=>"123", "K2"=>"123"}], [{"K3"=>"23", "K4"=>"32"}], [{"K5"=>"34", "K6"=>"23"}]]}]
I hope that helpful
You can simply do as below,
x.map { |z| z.values[0][0] }
# => [{"K1"=>"123", "K2"=>"123"}, {"K3"=>"23", "K4"=>"32"}, {"K5"=>"34", "K6"=>"23"}]

Resources