I'm trying to merge two arrays into one array consisting of objects created from the corresponding array items from the two original arrays:
Ex:
words = ['Toolbar', 'Vamoose', 'Arcade'];
clues = ['Strip of buttons', 'Get lost', 'Pinball wizards hangout'];
What I want:
output = [{'Toolbar', 'Strip of buttons'}, {'Vamoose', 'Get lost'}, {'Arcade', 'Pinball wizards hangout'}]
Any suggestions?
Figured it out:
let words = ['Toolbar', 'Vamoose', 'Arcade'];
let clues = ['Strip of buttons', 'Get lost', 'Pinball wizards hangout'];
let data = [];
words.forEach((obj, index) => {
obj = {
word: words[index],
clue: clues[index]
};
data.push(obj)
})
console.log(data)
[{
"word": "Toolbar",
"clue": "Strip of buttons"
},
{
"word": "Vamoose",
"clue": "Get lost"
},
{
"word": "Arcade",
"clue": "Pinball wizards hangout"
}]
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 am searching for a while now, how I could achieve to turn objects arrays into an array with only values. For example, I have an array with several Restaurants and within these restaurants there is a key named category. Category could have multiple values like Sushi, Chinese, asian. I would like to go trough all object and reduce my array from:
[{
id: '1',
title: 'Italian Dream',
category: 'Pizza, Pasta, Snack',
opening_hours: '08:00-24:00',
},
{
id: '2',
title: 'Turkish Man',
category: 'Döner, Pizza, Lahmacun',
opening_hours: '08:00-24:00',
}]
to
[ Pasta, Snack, Döner, Pizza, Lahmacun]
Would be glad if anybody could give me any advice.
Cheers
Since category is a string and not an array of strings, we need to .split(', ')
Since we have multiple categories per data item, we can use .flatMap to "combine" or flatten that what would have been an array of arrays
We can use new Set(...) to get a unique list of string values
And finally use Array.from(...) to convert the Set to an Array.
const data = [{
id: '1',
title: 'Italian Dream',
category: 'Pizza, Pasta, Snack',
opening_hours: '08:00-24:00',
},
{
id: '2',
title: 'Turkish Man',
category: 'Döner, Pizza, Lahmacun',
opening_hours: '08:00-24:00',
}
]
const categories = Array.from(new Set(data.flatMap(x => x.category.split(', '))))
console.log(categories)
You can loop your array and use split function to extract categories from your string.
let newArray = [];
oldArray.forEach(restaurant => {
newArray.push(...restaurant.category.split(', '));
});
// Here newArray contains categories with duplicate values
// You can use Set to avoid duplicate values.
newArray = [...new Set(newArray)];
I have two arrays one with field names and the other array is having a list of arrays where each array corresponds to row in table.How can i use these two arrays to create a list of JSON Objects. Is there any in built function. I am able to acheive this using map/reduce/ for -loop but this is impacting the performance if the second array is having more rows as we have traverse through each row.
I hope the following explains the use case better. Please share the sample code if possible.
Arr1=[field1,field2];
Arr2=[[1,2],[3,4],[5,6]];
Expected Output:
[
{
field1 :1 ,
field2: 2
},
{
field1 :3 ,
field2: 4
},
{
field1 :5 ,
field2: 6
}
]
You can use Array.map to map the elements
const mapFields = (arr1, arr2) => {
const mappedArray = arr2.map((el) => {
const mappedArrayEl = [];
el.forEach((value, i) => {
if (arr1.length < (i+1)) return;
mappedArrayEl[arr1[i]] = value;
});
return mappedArrayEl;
});
return mappedArray;
}
const Arr1 = ["field1","field2"];
const Arr2 = [[1,2],[3,4],[5,6]];
console.log(mapFields(Arr1, Arr2));
I have a list of arrays i need to hide the duplicates of array
{
"company_name": "SERVICE INDUSTRIES LTD.",
"claim_id": "2017\/04\/LHRHHDP00015-2018-00702",
},
{
"company_name": "KARACHI CHAMBER OF COMMERCE & INDUSTRY",
"claim_id": "2018\/03\/HOHHDP00013-2019-00098",
},
{
"company_name": "PAKISTAN RED CRESCENT SOCIETY",
"claim_id": "2017\/04\/LHRHHDP00015-2018-00702",
},
{
"company_name": "SERVICE INDUSTRIES LTD.",
"claim_id": "2018\/04\/LHRHHDP00022-2019-01292",
},
{
"company_name": "U MICROFINANCE BANK LTD",
"claim_id": "2017\/04\/LHRHHDP00015-2018-00702",
}
This is the example array i need to hide the array which have duplicate claim_id.
You can use a filter and findIndex to find duplicates. If the index does not equal the current item, there is a duplicate.
The performance impact is maximum 1.5x the size of the array:
const unique = data.filter((item, index) =>
data.findIndex(({ claim_id }) => item.claim_id === claim_id) === index
);
To solve this easily let's use this strategy:
Extract values from the array to an object (used as a dictionary)
Eliminating duplication
Extract values to a new array
so....
const dic = {}
for (const item of originalArray) {
dic[item.claim_id] = item
}
const groupedArray = Object.values(dic)
The only question is... where's typescript? we used native JS and managed just fine :)
"name": [
{
"name": "test1"
},
{
"name": "test2"
},
{
"name": "test3"
},
{
"name": "test1"
},
]
I have the above created by nodejs. During array push, I would like to remove duplicated arrays from the list or only push the name array if the individual array does not exist.
I have tried below codes but it changes the array.
var new = [];
for (var i =0;i<name.length;i++){
new['name'] = name[i].name;
}
The easiest way is probably with Array.prototype.reduce. Something along these lines, given your data structure:
obj.name = Object.values(obj.name.reduce((accumulator, current) => {
if (!accumulator[current.name]) {
accumulator[current.name] = current
}
return accumulator
}, {}));
The reduce creates an object that has keys off the item name, which makes sure that you only have unique names. Then I use Object.values() to turn it back into a regular array of objects like in your data sample.
the solution can be using temp Set;
const tmpSet = new Set();
someObj.name.filter((o)=>{
const has = tmpSet.has(o.name);
tmp.add(o.name);
return has;
});
the filter function iterating over someObj.name field and filter it in place if you return "true". So you check if it exists in a tmp Set & add current value to Set to keep track of duplicates.
PS: new is a reserved word in js;
This should do it
const names = ['John', 'Paul', 'George', 'Ringo', 'John'];
let unique = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
https://wsvincent.com/javascript-remove-duplicates-array/