Filtering result using Javascript - javascript

I am trying to filter an array, but am having issues with returning only the values which are true (status: yes).
var arr = {
"status": "Yes"
},
{
"status": "No"
},
{
"status": "No"
},
{
"status": "No"
}
var filteredResult = [];
for (var i = 0; i < arr.length; i++) {
if(arr[i].status == "Yes") {
filteredResult.push(status);
}
}
console.log (filteredResult);
I am still learning JS, but I hope to improve.
Thank you.

I don't think this code compiles - you need to include square brackets to declare an array.
const arr =
[{ "status": "Yes" },
{ "status": "No" },
{ "status": "No" },
{ "status": "No" }]
Then to filter it, just do
const results = arr.filter((item) => { return item.status === "Yes" })

Your syntax is wrong so for loop won't work. The array should be inside "[]". Refer to the below code. I have tested and is working fine.
If you want to get list of all object having status "Yes", then use filteredResult.push(arr[i]), else filteredResult.push(arr[i].status) if you need strings of "Yes"
var arr = [{
"status": "Yes"
},
{
"status": "No"
},
{
"status": "No"
},
{
"status": "No"
}]
var filteredResult = [];
for (var i = 0; i < arr.length; i++) {
if(arr[i].status == "Yes") {
filteredResult.push(arr[i]);
}
}

Related

Search if a String has a subset string present in array of object javascript

Looking for the optimal solution to find a string inside an array of objects.
Let's say I have a variable that holds a result which I get from an API call
let result = "485178485451478"
I have to search the above result in the below array of objects & see if the substring in the array matches the result. If the result matches I simply want to return true.
const arrayCode = [
{
"code": "2150"
},
{
"code": "4857"
},
{
"code": "5046"
},
{
"code": "4851"
},
{
"code": "4154"
},
{
"code": "9654"
},
{
"code": "1254"
},
{
"code": "9562"
},
{
"code": "1457"
},
{
"code": "6479"
}]
So here in the above problem if I write a code, it should return me an index of 3.
Below is the basic code which I wrote to get the solution. But what if the array length is too long? Looking for the optimal solution. Thanks
Below is the code:
let result = "485178485451478"
let index = 0
for(let i= 0; i< arrayCode.length;i++){
let flag = result.indexOf(arrayCode[i].code);
if(flag===0){
index = i;
break;
}
}
console.log(index)
You can simply achieve this requirement with a single line of code with the help of Array.some() method along with String.indexOf()
Live Demo :
let result = "485178485451478";
const arrayCode = [
{
"code": "2150"
},
{
"code": "4857"
},
{
"code": "5046"
},
{
"code": "4851"
},
{
"code": "4154"
},
{
"code": "9654"
},
{
"code": "1254"
},
{
"code": "9562"
},
{
"code": "1457"
},
{
"code": "6479"
}
];
const res = arrayCode.some(({ code }) => result.indexOf(code) !== -1);
console.log(res);
The some function will iterate only until it finds the first occurrence, so you could use along with the includes function:
const included = (element) => result.includes(element.code);
console.log(arrayCode.some(included));
here is What I would do:
let index = 0
arrayCode.forEach((e, indx) => {if(result.indexOf(e.code) == 0)index = indx;});
console.log(index)
Hope to help!

How would I filter an array of objects by : If id numbers are consecutive

I have a JSON file that has an array of objects with data inside :
[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden#xerex.com",
"nameList": [
{
"id": 0,
"name": "Wendi Mooney"
},
{
"id": 2,
"name": "Holloway Whitehead"
}
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [
{
"id": 0,
"name": "Janine Barrett"
},
{
"id": 1,
"name": "Odonnell Savage"
},
{
"id": 2,
"name": "Patty Owen"
}
]
}, ...
My job is to filter the arrays that have more than two names and if their id are consecutive.
I managed to sort users with more than two user.name but cant grasp the concept of filtering consecutive id numbers
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
Which returns me the objects with more than two user names.
filter takes a function that returns true if you want to retain the item or false if not. In this function, you could check the length of the nameList, and then iterate over its members and make sure their ids are consecutive:
retult = userData.filter(u => {
if (u.nameList.length < 2) {
return false;
}
for (let i = 1; i < u.nameList.length; ++i) {
if (u.nameList[i].id != u.nameList[i - 1].id + 1) {
return false;
}
}
return true;
});
a item should need tow conditions,one is nameList length is two ,the other is the itemId of nameList is consecutive;
so first as you do :
`
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
`
;
then
`
let lister4 = lister3.filter(names=>{
let idOfStr = names.nameList?.sort((a,b)=>a.id-b.id).map(item=>item.id).join("");
let resultStr = Array.from(idOfStr.length).fill(+idOfStr[0]).map((item,index)=>+item+index).join('');
return idOfStr === resultStr
})
`
hope this is useful for you

right way to add an object into array with looping through

i know it is a repeated Question but i can't figure the proper way to add an object to an array with checking if there is match or not like , this is a function that loops through an array of words and check if the entered word is in the array so increase its count by 1 , if not push this word to the array
and set its count by 0
function addWord(request, response) {
var data = request.params;
var word = data.word;
var reply;
for (i = 0; i < Words.length; i++){
if (Words[i].type != word){
reply = {
msg: "not Found but added"
};
Words.push({"type": word , "count": 0});
} else if (Words[i].type == word) {
reply = {
msg: "already Found and added"
};
Words.count++;
}
}
var x = JSON.stringify(Words, null, 2);
fs.writeFile('count.json', x, finished);
function finished(){
console.log('Yay')
}
the problem is the output gives me four new elements not just one and with Count 1 not 0, lets say that i added the word Music the output is like so
[
{
"type": "physical",
"count": 8
},
{
"type": "WCAP",
"count": 2
},
{
"type": "BLQ",
"count": 2
},
{
"type": "unable",
"count": 2
},
{
"type": "music",
"count": 1
},
{
"type": "music",
"count": 1
},
{
"type": "music",
"count": 1
},
{
"type": "music",
"count": 1
},
]
The problem is that you first must loop over all the words before deciding if a word is in the list or not. You could fix your code to look like this:
var found = false
for (i = 0; i < Words.length; i++){
if (Words[i].type == word){
Words[i].count++
reply = {
msg: "already Found and added"
};
found = true;
break;
}
}
if (!found) {
Words.push({"type": word , "count": 0});
reply = {
msg: "already Found and added"
};
}
And just in case, here is a snippet with a simpler addWord function that might help you:
var Words = [];
function addWord(word) {
for (var i=0; i < Words.length; i++) {
if (word == Words[i].type) {
Words[i].count++
return
}
}
Words.push({type: word, count: 0})
}
addWord('stack')
addWord('overflow')
addWord('stack')
console.log(Words)
try the following function:
function findWord(Words) {
let found = Words.some(word => word.type == yourWord)
return found;
}

Removing Duplicate object from array in jquery code not working

This is my array in jquery , which contains duplicate objects/elements :
[{
"name": "hello",
"label": "world"
}, {
"name": "abc",
"label": "xyz"
}, {
"name": "hello",
"label": "world"
}]
I am using the following piece of code to remove duplicate elements but it not working the duplicate elements are not removed.
var result = [];
$.each(subservices, function (i, e) {
if ($.inArray(e, result) == -1)
result.push(e);
});
alert(JSON.stringify(result));
Function $.inArray works fine for simple types (e.g. number or string), but for complex types it does not produce the correct result, because it tries to match by reference. Instead of using inArray in your loop you can search the array using function grep:
var subservices = [{
"name": "hello",
"label": "world"
}, {
"name": "abc",
"label": "xyz"
}, {
"name": "hello",
"label": "world"
}
];
var result = [];
$.each(subservices, function (i, e) {
var matchingItems = $.grep(result, function (item) {
return item.name === e.name && item.label === e.label;
});
if (matchingItems.length === 0){
result.push(e);
}
});
//displays result [{"name":"hello","label":"world"},{"name":"abc","label":"xyz"}]
alert(JSON.stringify(result));
Here is a working jsFiddle
You need to filter array by unique name/value. Here is some pure JS solution:
var data = [{
"name": "hello",
"label": "world"
}, {
"name": "abc",
"label": "xyz"
}, {
"name": "hello",
"label": "world"
}];
var result = data.filter(function(el, i, x) {
return x.some(function(obj, j) {
return obj.name === el.name && (x = j);
}) && i == x;
});
alert(JSON.stringify(result, null, 4));
This is because these two objects are distinct, even though all the attributes inside are the same. You can see this from:
console.log(result[0] === result[2]);
which results in false.
Instead, you need to iterate through your array based on a unique identifier, such as name & label as such:
for(var i = 0, i < results.length; i++) {
if (result[i].name === ... && result[i].label === ...) {
index = i;
break;
}
}
to check if your item is unique.

JSON Data Fuzzy merge

I have a JSON data like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
},
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
}
}
I need to search for fuzzy data and merge. For example InvestmentsDeposits and InvestmentsDeposits$$$d need to be merged because it matches closely in name
Need to use javascript for this
For now I can make sure source data will always have $$$d at the end to merge with the target data without $$$d i.e., InvestmentDeposits.
My final merged content should be like this
{
"array": {
"InvestmentsDeposits": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
"text": "newtext"
}
]
}
}
}
any help on this one?
What I have tried so far
var json0 = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"PARENT": [
{
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}
]
}
};
var json1 =
{
"InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"PARENT": [
{
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
}
]
}
};
// Merge object2 into object1, recursively
$.extend( true, json0, json1 );
I am able to merge the data if i am able to split the InvestmentDeposits and InvestmentDeposits$$$d in to two distinct JSON objects but how to split and move the $$$d data in to another object? to make the jquery extend work
Use Object.keys() to find an object's keys and figure out what data to move over. You can compare the first key with the others to find matches, then remove the keys you just looked at until all of them are gone. Here's an example with a similar object.
var dat = {
"InvestmentsDeposits": {
"NAME": "Investments & Deposits",
"CONTENT_ID": "Promotions",
"DISPLAY_ORDER": 3,
"PATH": "/Promotions"
}, "InvestmentsDeposits$$$d": {
"NAME": "Deposits",
"CONTENT_ID": "NewPromotion",
"text" : "newtext"
},
"NotLikeTheOthers": {
"Um": "Yeah."
}
};
var result = {}; // This will be the merged object
var keys = Object.keys(dat); // Contains keys
while(keys.length) {
var i=1;
for(; i<keys.length; i++) { // Find matches
if(keys[0] == keys[i] + '$$$d') { // Match type 1
result[keys[i]] = dat[keys[i]]; // Copy orig
for(var j in dat[keys[0]]) { // Replace values
result[keys[i]][j] = dat[keys[0]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
} else if(keys[i] == keys[0] + '$$$d') { // Reverse matched
result[keys[0]] = dat[keys[0]];
for(var j in dat[keys[i]]) {
result[keys[0]][j] = dat[keys[i]][j];
}
keys.splice(i,1);
keys.shift();
i = 0;
break;
}
}
if(i > 0) { // Didn't find a match
result[keys[0]] = dat[keys[0]];
keys.shift();
}
}
alert(JSON.stringify(result));
Note that Object.keys() requires IE9+.

Categories

Resources