How to convert a set of strings into 'ONE' array in JavaScript? - javascript

I have some data in a form of string and I want them to be inside an array so I can filter them.
I've tried .split() but it created individual arrays NOT one array with all the data inside it.
This is how the part of data looks.
"Jane Doe"
"John Smith"
"Rose Benet"
list goes on
What is the best way to convert these strings into one array?
Here's what I've tried.
for (let i = 0; i < customerData.length; i++) {
let arrays = customerData[i].name;
function flatten(arr) {
return [].concat(...arr);
}
console.log(flatten(arrays));
}
And the result was rather than adding all strings nicely into one array, it gave each string its own array like this.
Array(14)
0: "J"
1: "a"
2: "n"
3: "e"
4: " "
5: "D"
6: "o"
7: "e"
length: 8
Array(11)
0: "J"
1: "o"
2: "h"
3: "n"
4: " "
5: "S"
6: "m"
7: "i"
8: "t"
9: "h"
length: 10
list goes on
The desirable result would be:
['Jane Doe', 'John Smith', "Rose Benet" list goes on]
This is how 'CustomerData' is defined:
CustomerData = [
{
"index": 0,
"name" : "A",
"gender" : "male",
"company" : "CC"
},
{
"index": 1,
"name" : "B",
"gender" : "female",
"company" : "DD"
}]
Here's what I have tried so far. In my React app, I want to make a search box so users can put in search term than filtered result will be displayed.
This is the React code.
state = {
names: [],
searchTerm: ''
}
editSearchTerm = (e) => {
this.setState({ searchTerm: e.target.value });
}
dynamicSearch = () => {
for(let i = 0; i < customerData.length; i++) {
this.setState({ names: customerData[i].name });
}
return this.state.names.filter(name =>
name.toLowerCase().includes(this.state.searchTerm.toLocaleLowerCase()))
}
And when I try to type in some search term, React throws an error "TypeError: this.state.names.filter is not a function".
I assume the error msg means 'name' property should be an array. When I inspect in Chrome dev tool, 'customerData[i].name' returns as strings.
This is where I got stuck. I can't seem to get "name" values inside an array.
They either get into an array of their own, (so rather than Array(63), it shows Array(1), Array(1), Array(1)......in console.)
How can I convert 'customerData[i].name' into one array?

Or if you have the names in one variable, for instance:
const names = "Alex Kyle Aaron";
You can do:
const arrayOfNames = names.split(" ");
console.log(arrayOfNames); // ["Alex", "Kyle", "Aaron"]
Hope that helped! Good luck.

Just do this:
const arr = ["Jane Doe", "John Smith", "Rose Banet"]
Javascript can simply create an array with [] and of course you can put data into there delimiting with several commas.

Would this help?
var data = `
Test Name
Pizza Cheese
Hello World
`;
console.log(data.split('\n').filter(n => n != ''));

let stringValue='Jane Doe John Smith Rose Benet';
let stringList = stringValue.split(' ');
let resultList=[];
stringList.forEach((item,index)=> { if(index%2){ resultList.push(stringList[index-1]+' '+item); } });
console.log(resultList);
resultList => ["Jane Doe", "John Smith", "Rose Benet"]

Given the structure of customerData you can get an array containing the "name" property of every object in customerData simply with:
customerData.map(customer => customer.name);
In action:
let customerData = [
{
"index": 0,
"name" : "A",
"gender" : "male",
"company" : "CC"
},
{
"index": 0,
"name" : "B",
"gender" : "female",
"company" : "DD"
}];
console.log(customerData.map(customer => customer.name));

Related

Merge objects of array having same value of a key but keep different values of another key as inner array [duplicate]

This question already has answers here:
Group array items using object
(19 answers)
Closed 3 months ago.
I have an array which has keys eventId and selectedNumber. In the array same eventid can be present in multiple objects but selectedNumber value will be always different. My aim is to make a nested array in which each object will have unique eventId But selectedNumber will become an array having numbers from each of those objects having the same eventId. I tried using lodash _.groupBy() method but its just combines the objects into array and add it to the value with key as eventId. I don't want that. Anyway to do it?
Input:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "20"
},
{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "30"
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
Result:--
[{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : ["20", "30"]
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}]
let newarr = []
oldArr.map((x,i)=>{
if(i==0){
const numArr = []
numArr.push(x.selectedNumber)
delete x.selectedNumber
x.numArr = numArr newarr.push(x)
}else{
if(oldArr[i].eventId == oldArr[i-1].eventId){
const temp = x.selectedNumber
delete x.selectedNumber
newarr[i-1].numArr.push(temp)
}else{
const numArr = []
numArr.push(x.selectedNumber)
delete x.selectedNumber
x.numArr = numArr
newarr.push(x)
}
}
})
Just reduce your input to an object, and map the object entries to the desired array format:
const input = [{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "20"
},
{
"eventId" : "636939dde9341f2fbbc7256e",
"selectedNumber" : "30"
},
{
"eventId" : "63693a55e9341f2fbbc725c0",
"selectedNumber" : "50"
}];
const result = Object.entries(input.reduce((a, {eventId, selectedNumber}) => {
a[eventId] = a[eventId] || [];
a[eventId].push(selectedNumber)
return a;
}, {})).map(([eventId, selectedNumber]) => ({ eventId, selectedNumber }));
console.log(result);
Instead of creating the intermediate lookup object, you could directly reduce to an array, but it will have a negative impact on the solution's time complexity.

How to map over array of array and extracts another array object in javascript [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 6 months ago.
I have an array of array containg informations about the employe of a company.
The array look like this
[
[
"14578",==> employee number
"Marc", ==> employee name
"Paris",==> employee city
"ENGINEER",==> employee position
"24578963", ==> employee salary
"A" ==> employee team
],
[
"81832",
"Alan",
"Marseille",
"MECHANIC",
"25578963",
"C"
],
[
"39629",
"John",
"Lyon",
"PLUMBER",
"26578963",
"F"
]
]
And i want to each array , to get the first information (employee number ) and the fourth information (employee position)
desired output
[{"employee number": "14578","employee position": "ENGINEER"}, {"employee number": "81832","employee position": "MECHANIC"}, {"employee number": "39629","employee position": "PLUMBER"}]
I use map like this :
const myExtractArray = myInitialArray.map( elt =>
{
"employee number" : elt[0],
"employee number":elt[3]
return elt
}
);
But i doesn't get the desired output. How can i do this please ?
You're not returning anything from the map().
Also retur is a syntax error.
const data = [["14578", "Marc", "Paris", "ENGINEER", "24578963", "A"], ["81832", "Alan", "Marseille", "MECHANIC", "25578963", "C"], ["39629", "John", "Lyon", "PLUMBER", "26578963", "F"] ];
const result = data.map(o => {
return {
"employee number": o[0],
"employee position": o[3]
};
});
console.log(result);

Jquery Object and Array implementation

I have an Object
let data = {
a: 1,
b: 2,
c: {
abc: "ak",
bcd: "gh",
cfv: "ht"
}
}
then I have variables which I need to show with these object value
let abc = "first 1", bcd="sec2", cfv="third3" , def="fourth 4", tdf = "fifth 5";
Now the Object will come in API call it can be any of these variable.
How can I match the variable name with the object data.c.(object key) and concatinate their value.
for example the output should be
As we have (abc, bcd, cfv) as our object key then the output would be
first 1ak ==> that is the value of (abc + data.c["abc"])
sec2gh ==> that is the value of (bcd + data.c["bcd"])
third3ht ==> that is the value of (cfv + data.c["cfv"])
I tried using Object.keys() method so from this method we will get the object keys in array then how can I match with the variable name -
Object.keys(data.c);
==> ["abc", "bcd", "cfv"] (After this how can I proceed to match the variable and show their values?)
Shall I loop throught the object that (data.c)?
Please help me giving some ideas to achieve this implementation.
thank you
If it's possible for you to amend the format of your abc, bcd etc. variables to be the properties in an object, then this problem becomes trivial. You can use flatMap() to create a new array of the output values by linking the properties of the two target objects, like this:
let values = {
abc: "first 1",
bcd: "sec2",
cfv: "third3",
def: "fourth 4",
tdf: "fifth 5"
}
let data = {
a: 1,
b: 2,
c: {
abc: "ak",
bcd: "gh",
cfv: "ht"
}
}
let output = Object.keys(values).flatMap(k => data.c.hasOwnProperty(k) ? values[k] + data.c[k] : []);
console.log(output);

array difference in javascript

I know this will be so simple but I am trying this for two days so I finally decided to take help from you guys...
I have tried this probably the same question as mine but it is not giving me the answer.
ok so these are the two array
a = [{toNumber: "123", message: "Hi Deep "}, {toNumber: "321", message: "Test1"}]
b = [{toNumber: "321", message: "Test2"}, {toNumber: "123", message: "Hi Deep "}]
What I want is
diff = [{toNumber: "321", message: "Test2"}]
so quick help would be much appriciated.
So with your code you need to look at the other object and see if it has any keys that match. If it matches, you need to see if the message matches. So you can make a look up object that has the list of ids. You can than loop over your second array and see if they march.
var a = [
{toNumber: "123", message: "Hi Deep "},
{toNumber: "321", message: "Test1"}
]
var b = [
{toNumber: "321", message: "Test2"},
{toNumber: "123", message: "Hi Deep "}
]
// create the lookup from the first array
var lookup = a.reduce( function (lookUpObj, entryA) {
// set the object property with the toNumber property
lookUpObj[entryA.toNumber] = entryA.message
return lookUpObj
}, {})
// Now loop over the array and look for the differences
var diff = b.reduce(function (arr, entryB) {
// grab the entry from the lookup object we created
var orginalMessage = lookup[entryB.toNumber]
// if we do not have it listed OR the message is different
// add it to the list as changed.
if (!orginalMessage || orginalMessage !== entryB.message) {
arr.push(entryB)
}
return arr
}, [])
console.log(diff)
Now that will match any differences from a to b. If anything was removed in B that is not in A it will not be caught.
Where is the problem ???
const a =
[ { toNumber: "123", message: "Hi Deep " }
, { toNumber: "321", message: "Test1" }
]
const b =
[ { toNumber: "321", message: "Test2" }
, { toNumber: "123", message: "Hi Deep " }
]
const diff = b.filter(eB=>!a.some(eA=>( eA.toNumber===eB.toNumber
&& eA.message===eB.message )))
document.write( JSON.stringify( diff ) )

How to make an array of objects with different label and value in Reactjs

I am using this.state.student in react to display (name,school,class.etc)..
how i change the "school" display to "college" without replacing the value of "School" in the api..
as i am new to code i tried
'var student = [ {"name", "school", "class"}];'
'student[1] = "college";'
but this just replaces the value. i just want to change the display
of "school" please help
Check my code. I created a function addToArray that will accept a parameter of object then it will add it to the students array. This will give you an output of [{ name: "John Doe", school: "College", class: "A" }]
let students = [];
addToArray = student => {
students.push({
name: student.name,
school: student.school,
class: student.class
});
console.log(students);
};
this.addToArray({
name: "John Doe",
school: "College",
class: "A"
});
Use this to create an array of objects with different key and value pair,
var productArr = [];
productId = 1;
productName = 'Product Name';
productArr.push({ id: productId, name: productName });
Hope it'll work for you. Waiting for your response. Thank you!
You can try this:
var student = [ {"name": "school", "class":"XYZ"}];
student = [...student,{"name":"college","class":"ABC"}]
console.log(student)

Categories