I am trying to remove specific elements from an array based on data I'm getting from an API. The API returns an array of objects like this {"videoDate":"07/31/2020","videoTime":"1:00 AM"}. I have an existing array with items that look like this "07/31/2020 1:00 AM". My intention is to check if the existing array contains an item with a string matching both the videoDate and videoTime strings from the object and remove them.
let responseArray = JSON.parse(response);
responseArray.forEach((item) => {
dayArray.forEach((day) => {
if (day.includes(item.videoDate) && day.includes(item.videoTime)) {
let index = dayArray.findIndex(item => item.videoDate && item.videoTime);
dayArray.splice(index, 1);
}
});
});
console.log(dayArray);
The above code flags everything and returns an empty dayArray.
let responseArray = JSON.parse(response);
responseArray.forEach((item) => {
dayArray.forEach((day) => {
if (day.includes(item.videoDate) && day.includes(item.videoTime)) {
// ts-ignore
let index = dayArray.findIndex(item.videoDate && item.videoTime);
dayArray.splice(index, 1);
}
});
});
console.log(dayArray);
The above code throws an error TypeError: 1:00 AM is not a function
response.forEach((item) => {
dayArray.forEach((day) => {
if (day.includes(item.videoDate) && day.includes(item.videoTime)) {
// ts-ignore
let index = dayArray.findIndex(item.videoDate && item.videoTime);
dayArray.splice(index, 1);
}
});
});
console.log(dayArray);
The above code where I'm not parsing the response first returns response.forEach is not a function
Is there a better way to accomplish this?
I edited my previous solution, I believed, what you wanted to do is if the items (date and time) in the array matches any value in the returned object, remove the item from the array.
Test it and give feed back
let response = `[{"videoDate":"07/31/2020","videoTime":"1:00 AM"}]`
let dayArray = ["07/31/2020 1:00 AM"];
let responseArray = JSON.parse(response);
dayArray.forEach((el, i) => {
let item = el.split(/(^[^\s]*)\s/);
item.shift();
responseArray.forEach((obj) => {
let obj_vals = Object.values(obj);
if(obj_vals.indexOf(item[0]) != -1 && obj_vals.indexOf(item[1]) != -1 ) dayArray.splice(i, 1);
}); });
console.log(dayArray)
Related
Manager example
// Create a new array
var gryfindor = [];
// Loop through each wizard
wizards.forEach(function (wizard) {
// If the wizard is in Gryfindor, push to the new array
if (wizard.house === 'Gryfindor') {
gryfindor.push(wizard);
}
});
My manager asked me to write this thing into in this format below:
// Create a new array from the wizard array
var gryfindor = wizards.filter(function (wizard) {
// Only include wizards from the Gryfindor house
return wizard.house === 'Gryfindor';
});
I need to change the foeeach in JavaScript but I don't know how to do anyone can write it or encode
var isExist = false;
var cashoutIndex = 0;
CashOutData.forEach((item, index) => {
if (item.id === userBets[0][i].id) {
isExist = true;
cashoutIndex = index;
}
});
Change of for each loop and faster the performance
answer as per manager required format
Your code does not need to enumerate every item in the list in most cases.
The following code finds the index of the first matching element, and then constructs the response accordingly.
Boolean(~index) uses the bitwise NOT operator to convert the not found signal (-1) from findIndex to a falsy number (0).
const go = (data, userBets) => {
const index = data.findIndex(({id}, i) =>
id === userBets[0]?.[i]?.id)
return [ Boolean(~index), index === -1 ? 0 : index ]
}
const [ isExist, cashoutIndex ] = go(CashOutData, userBets)
I'm trying to manipulate the repeater list in Wix. When the user selects the quantity of equipment, that number of forms show up. I got the hang of it when I see it in the console log but when I try to display it on the web, it gives me an error. I've tried reassigning $w("#repeater1").data to newArr(the new data).
Here's my code
$w("#repeater1").hide();
let itemOptions = $w("#quoteDropdown").options
$w("#quoteDropdown").onChange((event) => {
$w("#repeater1").show();
const arrOfValues = []
let newArr = []
let repeaterData = $w("#repeater1").data;
let quantity = Number(event.target.value);
let iterator = repeaterData.values();
for(const value of iterator) {
arrOfValues.push(value);
}
for(let i = 0 ; i < itemOptions.length; i++) {
newArr = repeaterData.slice(0, quantity);
}
if(quantity > newArr.length) {
let newItems = arrOfValues.filter(arr => {
newArr.forEach(na => arr !== na)
})
newArr.push(newItems)
}
console.log("newArr");
console.log(newArr);
// $w("#repeater1").data is the original data from the repeater
// newArr is the altered data from the repeater based on how it appears based on the users' interaction.
// I've tried each one of these
// $w("#repeater1").data = newArr;
// return newArr;
}); // end onChange
If you're trying to assign the array as the data for a repeater, you need to follow some rules. First, it needs to be an array of objects. Second, each object needs to have an _id property.
I would like to know how to filter array of values using javascript
How to seperate the arrays with 'provider-send' and 'provider-receive'
var filterradio = id.filter(function(e){
return e.id.split("-")[0] == "provider-send"
})
var id=["provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund"]
Expected Output:
result_sn: ["provider-send-credit-transfer", "provider-send-debit-fund"]
result_rcn:["provider-receive-credit-transfer","provider-receive-debit-fund"]
If it's always going to be "provider-receive-..." and "provider-send..." then you can do the following to separate them
for (i = 0; i < id.length; i++) {
if (id[i].split("provider-send-").length > 1) {
result_sn.push(id[i]);
} else if (id[i].split("provider-receive-").length > 1) {
result_rcn.push(id[i])
}
}
Try This :
var id = [ "provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund" ] ;
var result_sn = [] , result_rcn = [] ;
for( value of id ) {
var twoWords = value.split('-',2).join('-') ;
if ( twoWords === "provider-send" )
result_sn.push( value ) ;
else if ( twoWords === "provider-receive" )
result_rcn.push( value ) ;
}
console.log( result_sn ) ;
console.log( result_rcn ) ;
Pass 2 as second parameter to split() and then again join() by -. The second parameter to split() specifies the max number of elements in the result array.
var id=["provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund"]
var filterradio = id.filter(function(id){
return id.split("-",2).join('-') === "provider-send"
})
console.log(filterradio)
Using .filter() will require you to write 1 filter for every pattern you want to match have assigned to a variable.
Using .reduce() is recommended and is more easily expandable to support more patterns.
It may look intimidating at first but you're essentially using accumulator as the temporary variable that gets stored and brought forward to each iteration. And each iteration of the array will give you the current iterated value with currentValue.
I've added something-else as an example of adding new pattern.
var id = [
"provider-send-credit-transfer",
"provider-send-debit-fund",
"provider-receive-credit-transfer",
"provider-receive-debit-fund",
"something-else-credit-transfer",
"something-else-debit-fund"
];
const {
'provider-send': result_sn,
'provider-receive': result_rcn,
'something-else': result_ste
} = id.reduce(function(accumulator, currentValue) {
let prefix = currentValue.match(/^\w+-\w+/)[0];
return {...accumulator, [prefix]: (accumulator[prefix] || []).concat(currentValue)}
}, {});
console.log(result_sn);
console.log(result_rcn);
console.log(result_ste);
I suggest using reduce instead of the filter as reduce is used to reduce the array size into a single returned element.
Here I am reducing the array into an object which has two keys result_sn and result_rcn.
var id = ["provider-send-credit-transfer", "provider-send-debit-fund", "provider-receive-credit-transfer", "provider-receive-debit-fund"]
const result = id.reduce((obj, str) => {
if (str.match(/^provider-send/g))
obj['result_sn'].push(str);
else
obj['result_rcn'].push(str);
return obj;
}, {
'result_sn': [],
'result_rcn': []
});
console.log(result)
I would like to check if an item.name already exists in the object array so it will not push that existing object to the array.
This is the piece of code:
loadedVariations.forEach(function(item){
console.log('item', item.name.indexOf(name));
if(name === tests[test].id && item.name.indexOf(name) < 0){
console.log(item.name)
loadedVariations.push({name: name, variation: variation});
tests[test].callback(name, variation);
console.log('tests', tests[test], variation, loadedVariations);
if(variation === '1'){
value = "control"
} else {
value = "variationb"
}
localStorage.setItem('gtmTest', JSON.stringify(loadedVariations));
}
})
This is the output in my localstorage:
gtmTest:
[{"name":"globalPassFrame_review","variation":"1"},
{"name":"globalPassFrame_review","variation":"1"},
{"name":"socialshare_bar","variation":"2"},
{"name":"socialshare_bar","variation":"2"}]
This is an AB Test in google tag manager with an helping script which runs on multiple test scripts so it runs multiple times that's why I need to check if item already exists in the object array so it doesn't push the same object twice.
Here is how do you can iterate over your json object by using every and match name . If you want to have array of unique Names you can iterate using forEach and check if it is not present in array .
var object = [{"name":"globalPassFrame_review","variation":"1"},{"name":"globalPassFrame_review","variation":"1"},{"name":"socialshare_bar","variation":"2"},{"name":"socialshare_bar","variation":"2"}];
var tobeFound='globalPassFrame_review';
object.every(function (elem, i) {
if(elem.name == tobeFound ){
console.log('element found at index '+i);
return false ;
}
});
// In case you want to store uniue Names
var uniqueNames=[];
object.forEach(function (elem, i) {
if(!uniqueNames.includes(elem.name)){
uniqueNames.push(elem.name);
}
});
console.log(`unique Names are ${uniqueNames}`);
// Using ES6 style of code.
const uniqueNamesArr = [...new Set( object.map(obj => obj.name)) ];
console.log(uniqueNamesArr);
My Code Scenario is:
var Employees= [{name:"Ram",htno:1245},{name:"mohan",htno:1246},
{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var seletedEmployees= [{name:"mohan"},{name:"ranga"}];
var employeesdataAfterremoveSelected = [?];
You can store selected employees names in an array and then filter Employees array and check if employee's name is in this array:
var employees= [{name:"Ram",htno:1245},{name:"mohan",htno:1246},{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var selectedEmployees= ["mohan","ranga"];
var result = employees.filter(emp => selectedEmployees.includes(emp.name));
console.log(result);
To programatically get array of strings instead array of objects, you can use map:
var seletedEmployees= [{name:"mohan"},{name:"ranga"}].map(emp => emp.name);
From the code you have given above i think this might work
$.each(student, function(key, value){
if(matchedvalues.indexOf(value.name) < 0)
{
employeesdataAfterremoveSelected.push(value.name);
}
})
Here is a one liner, decomposed to explain :
// Start by filtering the first array on a condition.
employeesdataAfterremoveSelected = Employees.filter(
// Map the array of selected employees to only return the name
e => seletedEmployees.map(_e => _e.name)
// use the includes function to check if the name is in the array
.includes(e.name)
);
In one line :
employeesdataAfterremoveSelected = Employees.filter(e => seletedEmployees.map(_e => _e.name).includes(e.name));
You can use the filter method, something like below (not tested)
var Employees = [{name:"Ram",htno:1245}, {name:"mohan",htno:1246}]
var SelectedEmployess = [{name:"Ram",htno:1245}]
// filter the items from the invalid list, out of the complete list
var employeesdataAfterremoveSelected = Employees.filter((item.name) => {
return !SelectedEmployess.has(item.name);
})
// get a Set of the distinct, valid items
var validItems = new Set(employeesdataAfterremoveSelected);
You can try this:
var Employees = [{name:"Ram",htno:1245},{name:"mohan",htno:1246},
{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var seletedEmployees = [{name:"mohan"},{name:"ranga"}];
var employeesdataAfterremoveSelected = Employees.filter(name => {
return (name.name !== seletedEmployees[0].name && name.name !== seletedEmployees[1].name)
})
console.log(employeesdataAfterremoveSelected)
var Employees= [{name:"Ram",htno:1245},{name:"mohan",htno:1246},
{name:"madhu",htno:1247},{name:"ranga",htno:1248}]
var seletedEmployees= [{name:"mohan"},{name:"ranga"}];
var employeesdataAfterremoveSelected = Employees.filter(function(val,index) { console.log(val.name)
return !(seletedEmployees.map(function(e) { return e.name; }).indexOf(val.name));
});