简体   繁体   中英

How do I split multiple strings in an array with Javascript?

I have an array that looks like this:

var myArray = [ "name1+data1" , "name2+data2" , "name3+data3", "name4+data4" ]

When the user enters name1 , I would like to open an alert box and display data1 , for name2 it should display data2 , and so on.

In order to do this, I was wondering how I could split all the strings without using more than one array? And how do I display only data1 when name1 is entered by the user? I've tried using myArray.split("+") but it does not work.

You could map the splitted strings and get an object form the key/value pairs.

 var array = ['name1+data1', 'name2+data2', 'name3+data3', 'name4+data4'], object = Object.fromEntries(array.map(s => s.split('+'))); console.log(object);

You could try implementing below function that takes two arguments. targetArray is the array to perform search and searchString is the string to search. In your case searchString would be name1 . The time complexity is based on the position of the element in the array O(K).

function findMatch(targetArray, searchString) {
  const targetElement = targetArray.find(item => {
    const leftSplit = item.split('+')[0];
    return leftSplit === searchString;
  });
  if (targetElement) {
    return targetElement.split('+')[1];
  } else {
    return null;
  }
}
  window.alert(
    findMatch([ "name1+data1" , "name2+data2" , "name3+data3", "name4+data4" ], 'name2')
  );
Alerts: "data2"

If it is an array, then you need to iterate through the array.

const output = myArray.filter(arrayItem => arrayItem.includes(userInput))[0].split('+')[0];

The time complexity here would be O(N+M), where N is length of array and M is the length of the string.

I think it would be better if myArray is maintained as a dictionary,

const myArray = {
    name1: 'data1',
    name2: 'data2',
    name3: 'data3'
}
const output = myArray[userInput];

The time complexity would be decreased to O(1)

You could use this snippet

var myArray = [ "name1+data1" , "name2+data2" , "name3+data3", "name4+data4" ];
var userValue = prompt('Valeur à rechercher...');
myArray.map((item) => { 
    if(~item.search(userValue) && userValue.length > 0){
        alert(item.split('+')[1]);
        return false;
    }
 })

So, here's an example where name1 and name2 have values, but not the others:

let pairs = [ "name1+data1" , "name2+data2" , "name3+", "name4+" ]

We can split each of those into two-element arrays:

let arr = pairs.map(p=>p.split('+'))

And filter out the ones with empty names:

arr = arr.filter(a=>a[1].length > 0)

arr.join("\n")  // "name1,data1
                //  name2,data2"

Does that do what you want?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM